Search code examples
c#binaryreader

C# BinaryReader end of Stream


I am wondering if it's a good practice to use the EndOfStreamException to detect the end of the BinaryReader stream> I don't want to use BaseStream.Length property or PeekChar as proposed here

C# checking for binary reader end of file

because I have to load it into memory (maybe because it's from Zip file) and enable some flags. Instead, this is what I'm doing:

using (ZipArchive zipArchive = ZipFile.OpenRead(Filename))
  using (BinaryReader fStream = new BinaryReader(zipArchive.Entries[0].Open()))
  {
    while(true){
    try
    {
      fStream.ReadInt32();
    }
    catch (EndOfStreamException ex)
    {
      Log.Debug("End of Binary Stream");
      break;
    }
}

}


Solution

  • That approach is fine. If you know you have a seekable stream you can compare its length to the number of bytes read. Note that FileStream.Length does not load the whole stream into memory.

    But that approach is appropriate for arbitrary streams.

    And don't worry about the cost of using exceptions in this case, as streams imply IO, and IO is orders of magnitude slower that exception handling.