I was trying to read a binary file, it was written in a certain pattern for example: string, string, byte
I surfed web and found this code:
while (br.BaseStream.Position<br.BaseStream.Length)
{
br.ReadString();
br.ReadString();
br.ReadByte();
}
Even though it is easy code I can’t understand what the underlying stream(BaseStream) means? Can somebody give me a brief explanation of it?
.NET offers different objects to read or write data. Basicly there are DataWriters and DataReaders that write or read into different streams. Streams are representing the data flow between the data source (e.g. a file) to your applications memory (or back).
To access the stream in a defined direction you can use readers or writers.
BinaryReaderis one example of an data reader. It is supposed to read binary data out of the stream. Streams usually inherit from a base class calledStream. There are different type of streams representing different data sources. For example aFileStreamreads or writes data into a file on the HDD, whereas aMemoryStreamreads or writes data into the RAM. So the implementation of a stream describes where the data is stored.DataReaders or DataWriters describe how the data is stored. For example your
BinaryReaderreads byte sequences, whereas aTextReaderreads text with a given encoding. But both can be used with the same stream.To come back to your question: Your
BinaryReaderreads binary data from a stream. TheBaseStreamproperty returns the instance of the stream the reader reads data from. This is why you need to initialize theBinaryReaderwith an stream instance. You cannot tell the computer to read binary data from nowhere! 😉