C# checking for binary reader end of file

There is a more accurate way to check for EOF when working with binary data. It avoids all of the encoding issues that come with the PeekChar approach and does exactly what is needed: to check whether the position of the reader is at the end of the file or not.

while (inFile.BaseStream.Position != inFile.BaseStream.Length)
{
   ...
}

Wrapping it into a Custom Extension Method that'll extend the BinaryReader class by adding the missing EOF method.

public static class StreamEOF {

    public static bool EOF( this BinaryReader binaryReader ) {
        var bs = binaryReader.BaseStream;
        return ( bs.Position == bs.Length);
    }
}

So now you can just write:

while (!infile.EOF()) {
   // Read....
}

:) ... assuming you have created infile somewhere like this:

var infile= new BinaryReader();

Note: var is implicit typing. Happy to found it - it's other puzzle piece for well styled code in C#. :D


This work for me:

using (BinaryReader br = new BinaryReader(File.Open(fileName,   
FileMode.Open))) {
            //int pos = 0;
            //int length = (int)br.BaseStream.Length;
            while (br.BaseStream.Position != br.BaseStream.Length) {
                string nume = br.ReadString ();
                string prenume = br.ReadString ();
                Persoana p = new Persoana (nume, prenume);
                myArrayList.Add (p);
                Console.WriteLine ("ADAUGAT XXX: "+ p.ToString());
                //pos++;
            }
        }