Question

Possible Duplicate:
C# Reading a File Line By Line
How to loop over lines from a TextReader?

I am given a .NET TextReader (a class that can read a sequential series of characters). How can I loop over its content by line?

Was it helpful?

Solution

Do you mean something like this?

string line = null;
while((line = reader.ReadLine()) != null) 
{
    // do something with line
}

OTHER TIPS

You can create an extension method very easily so that you can use foreach:

public static IEnumerable<string> ReadLines(this TextReader reader)
{
    string line = null;
    while((line = reader.ReadLine()) != null) 
    {
        yield return line;
    }
}

Note that this won't close the reader for you at the end.

You can then use:

foreach (string line in reader.ReadLines())

EDIT: As noted in comments, this is lazy. It will only read a line at a time, rather than reading all the lines into memory.

The non-lazy solution I have at the moment:

foreach(string line in source.ReadToEnd().Split(Environment.NewLine.ToArray(),StringSplitOptions.None))

You'd use it like this:

string line;
while ((line = myTextReader.ReadLine()) != null)
{
    //do whatever with "line";
}

OR

string Myfile = @"C:\MyDocument.txt";
using(FileStream fs = new FileStream(Myfile, FileMode.Open, FileAccess.Read))
{                    
    using(StreamReader sr = new StreamReader(fs))
    {
        while(!sr.EndOfStream)
        {
            Console.WriteLine(sr.ReadLine());
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top