These classes are used to read and write primitive data types and strings. If you deal only with primitive types, this is the best stream to use. Remember that this data is not easily readable by a human eyeing its contents since the data is read in its binary form.
Table 6.13 lists some of the read and write methods.
c![table-6.13.gif]()
Table 6.13: Some Methods of the BinaryReader and BinaryWriter Classes
The BinStream class shown in Listing 6.12 is again similar to the StreamRW class from Listing 6.10, with the distinction that the user profile here is stored in binary format.
Listing 6.12: BinaryReader and BinaryWriter Example
![outputListitng6.12.gif]()
Output of above Listing 6.12.
This example has defined a class called BinStream that has two methods: Writer and Reader. The Writer method creates a FileStream object on the file called aboutme.txt and then creates a BinaryWriter from the FileStream object. Then some primitive variables are written to the file using the Write method from the BinaryWriter class. Finally, the BinaryWriter is closed. The Reader method creates a FileStream object on the file previously written (aboutme.txt) in Read mode. A BinaryReader class is instantiated using the FileStream object. The different overloads of the Read method of the BinaryReader class are used to read different primitive data types from the file. Finally, the read values are displayed on the console and the stream is closed.
Conclusion
Hope this article would have helped you in understanding BinaryReader and BinaryWriter Classes in C#. See other articles on the website on .NET and C#.