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?
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?
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.
yield return line? Is this... copied from another anwswer? 8-oThe 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()); } } }
TextReaderyou cannot be sure that you actually read "all" lines. If someone calls any of theRead*()methods before passing you the reference, you won't know. Whether that is an issue, YMMV.TextReader.ReadLineMethod