Reading and writing binary files in c sharp
Quite a bit has been written about reading structured binary data from or writing it to files see [1,2,3].
Now, if you wanted to accomplish the same with C A stream always requires a byte array as the target for read operations. Or if you use a BinaryReader the ReadBytes method returns a byte array.
In any case the data read into a byte array needs to be copied into the target struct. PtrToStructure to do this, and  offers a much more elegant solution using an unsafe assignment like this:. Alternatively you could read data from an input stream in little chunks using a BinaryReader , which would mean you deserialize the data into each field by hand.
This avoids the extra copy of data, but requires much effort on your side. However, due to a customer engagement I recently started thinking about this.
The approaches found in the literature, though, are too slow for him. I felt challenged by this problem. Look at the following code for reading the ID3v1 tag of a MP3 file:. And no extra copies of data are needed. Creating a sequential-access file. Reading a sequential-access file. BinaryWriter and BinaryReader classes for the writing and reading of primitive types. Working with the BinaryWriter Class. Working with the BinaryReader Class. File pointer move and read binary file.
Write and then read back binary data. Use BinaryReader and BinaryWriter to implement a simple inventory program. Here's a method which you can use if you want to read from a stream into the whole of an array, not stopping until it's finished:. Sometimes, you don't know the length of the stream in advance for instance a network stream and just want to read the whole lot into a buffer. Here's a method to do just that:.
While the above is simple, it's not terribly efficient, as it ends up copying the data at the very end, and probably several times between. Here's some code which works well if you know the expected length of data to start with. While you could use Stream.