Search code examples
c#.netfile-iostreamreadertextreader

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?


Solution

  • 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.)