How to use C# BinaryWriter Class

BinaryWriter object operates at a lower level of streams. It is specifically designed for writing primitive types as binary values to a specified encoding stream. By utilizing the BinaryWriter class, you can work directly with Stream objects, which grant access to the underlying bytes of the data being processed.

BinaryWriter class

To create a BinaryWriter object, you must first instantiate a FileStream object and then pass it as a parameter to the constructor method of the BinaryWriter class. This establishes the necessary connection between the BinaryWriter object and the underlying stream, enabling the writing of binary data.

FileStream writeStream ; writeStream = new FileStream("c:\\testBinary.dat", FileMode.Create); BinaryWriter writeBinay = new BinaryWriter(writeStream);

The primary advantage of using binary information is that it is not easily human-readable, providing a level of data security and obfuscation. Storing files in binary format also promotes optimal utilization of storage space, making it a best practice for efficient storage management.

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 writeStream ; try { writeStream = new FileStream("c:\\", FileMode.Create); BinaryWriter writeBinay = new BinaryWriter(writeStream); writeBinay.Write(" binary writer test"); writeBinay.Close(); } catch (Exception ex) { MessageBox.Show (ex.ToString()); } } } }

BinaryReader you can use in the same way to read as binary.


Utilizing of the BinaryWriter object and working with binary data, you gain enhanced control over data representation, security, and storage efficiency within your C# applications.