Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues using StreamReader.EndOfStream?

So I'm doing a project where I am reading in a config file. The config file is just a list of string like "D 1 1", "C 2 2", etc. Now I haven't ever done a read/write in C# so I looked it up online expecting to find some sort of rendition of C/C++ .eof(). I couldn't find one.

So what I have is...

TextReader tr = new StreamReader("/mypath");

Of all the examples online of how I found to read to the end of a file the two examples that kept occurring were

while ((line = tr.ReadLine() != null)

or

while (tr.Peek() >= 0)

I noticed that StreamReader has a bool EndOfStream but no one was suggesting it which led me to believe something was wrong with that solution. I ended up trying it like this...

while (!(tr as StreamReader).EndOfStream)

and it seems to work just fine.

So I guess my question is would I experience issues with casting a TextReader as a StreamReader and checking EndOfStream?

like image 728
MattMacdonald Avatar asked Sep 17 '25 10:09

MattMacdonald


2 Answers

One obvious downside is that it makes your code StreamReader specific. Given that you can easily write the code using just TextReader, why not do so? That way if you need to use a StringReader (or something similar) for unit tests etc, there won't be any difficulties.

Personally I always use the "read a line until it's null" approach - sometimes via an extension method so that I can use

foreach (string line in reader.EnumerateLines())
{
}

EnumerateLines would then be an extension method on TextReader using an iterator block. (This means you can also use it for LINQ etc easily.)

like image 168
Jon Skeet Avatar answered Sep 19 '25 23:09

Jon Skeet


Or you could use ReadAllLines, to simplify your code:

http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx

This way, you let .NET take care of all the EOF/EOL management, and you focus on your content.

like image 23
jv42 Avatar answered Sep 20 '25 00:09

jv42