How to use C# BinaryReader Class

The C# BinaryReader Object operates at a lower level of Streams, allowing for reading of primitive types as binary values within a specified encoding stream. It specifically works in conjunction with Stream Objects, which provide access to the underlying bytes of a data source. In order to create a BinaryReader Object, it is necessary to first instantiate a FileStream Object and then pass it as a parameter to the BinaryReader's constructor method.

FileStream readStream ; readStream = new FileStream("c:\\testBinary.dat", FileMode.Open); BinaryReader readBinary = new BinaryReader(readStream);

Utilizing Binary information has several advantages, with one notable benefit being its efficient utilization of storage space. By storing files in binary format, space usage is optimized, enabling more effective storage and retrieval of data. This practice is considered a best practice in terms of space optimization.

BinaryReader Object

By employing the capabilities of the BinaryReader Object, developers can efficiently read and extract binary data from streams, allowing for precise manipulation and interpretation of binary values. This can be particularly useful in scenarios where the underlying data is represented in a binary format, such as when working with image files, serialized objects, or other data structures that utilize binary encoding.

Full Source C#
using System; using System.Windows.Forms; using System.IO; using System.Text; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { FileStream readStream ; string msg = null; try { readStream = new FileStream("c:\\csharp.net-informations.dat", FileMode.Open); BinaryReader readBinary = new BinaryReader(readStream); msg = readBinary.ReadString(); MessageBox.Show(msg); readStream.Close(); } catch (Exception ex) { MessageBox.Show (ex.ToString()); } } } }

Conclusion

The C# BinaryReader Object offers a valuable tool for working with binary data at a lower level of Streams. Its ability to read primitive types as binary values and its compatibility with Stream Objects enable developers to effectively process binary information and optimize storage space utilization within their C# applications.