0

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?

Community
  • 1
  • 1
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
  • Note that given a `TextReader` you cannot be sure that you actually read "all" lines. If someone calls any of the `Read*()` methods before passing you the reference, you won't know. Whether that is an issue, YMMV. – Christian.K Oct 02 '12 at 10:08
  • 3
    My answer would be the same as [last time you asked](http://stackoverflow.com/questions/12687453/how-to-loop-over-lines-from-a-textreader/12687525#12687525) – Rawling Oct 02 '12 at 10:10
  • 1
    I wonder why it was so difficult to find it in the docs: [`TextReader.ReadLine` Method](http://msdn.microsoft.com/en-us/library/system.io.textreader.readline.aspx) – Tim Schmelter Oct 02 '12 at 10:14

4 Answers4

4

Do you mean something like this?

string line = null;
while((line = reader.ReadLine()) != null) 
{
    // do something with line
}
Tudor
  • 61,523
  • 12
  • 102
  • 142
2

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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());
        }
    }
}
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
0

The non-lazy solution I have at the moment:

foreach(string line in source.ReadToEnd().Split(Environment.NewLine.ToArray(),StringSplitOptions.None))
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465