1

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?

3
  • 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. Commented Oct 2, 2012 at 10:08
  • 3
    My answer would be the same as last time you asked Commented Oct 2, 2012 at 10:10
  • 1
    I wonder why it was so difficult to find it in the docs: TextReader.ReadLine Method Commented Oct 2, 2012 at 10:14

4 Answers 4

4

Do you mean something like this?

string line = null; while((line = reader.ReadLine()) != null) { // do something with line } 
Sign up to request clarification or add additional context in comments.

Comments

3

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.

6 Comments

Don't you mean yield return line? Is this... copied from another anwswer? 8-o
@Rawling: Yes, I did mean that. And yes, I copied the boilerplaet bit :)
@ChibuezeOpata: Yes, this is lazy - now I've added the yield return properly!
I'm loving the duality of "lazy" here :p
nice. though I think one of the readline's missing an s.
|
0

The non-lazy solution I have at the moment:

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

1 Comment

Why don't you put this in your original question?
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()); } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.