There is a binary file from which reading is byte-by-byte. How to know the end of the file? I know about the PeekChar () method, but in my case it does not fit, because I do not read the text, but the serialized object of the class. You can, of course, know the initial length of the byte array that represented the serialized object, but if there is no way to know it?

  • Show your code. How exactly do you turn bytes from a file into an object? - VladD

1 answer 1

Why not read the entire file?

byte[] fileBytes = File.ReadAllBytes("..."); 

In this case, you do not need to worry about reaching the end of the file.


If you need exactly using BinaryReader , then you can use the Position and Length properties of the data stream from which it reads:

 using (var stream = new FileStream("...", FileMode.Open, FileAccess.Read, FileShare.Read)) using (var reader = new BinaryReader(stream)) { bool endOfStream = stream.Position == stream.Length; // Либо: // bool endOfStream = reader.BaseStream.Position == reader.BaseStream.Length; }