136-c-sharp-binary-read-and-binary-write

In order to access binary file from C# it is comfortable to use OpenFileDialog class. To handle binary, either to read binary file or to write to binary file in C#, we need to use System.IO namespace. Inside System.IO namespace there is FileStream class that is necessary for handling binary data. We also need byte array for storing read data. Code goes like this:

FileStream fsBinaryRead = new FileStream(openFileDialog1.FileName,FileMode.Open);

It is essential to define object mode appropriately (mode Open for reading, instead of Create).

We also need to know size of the data to be read before we create byte array.
var var_data_size = (int) fsBinaryRead.Length;

Now, byte array can be crated as instance of byte[] class
byte[] bytData = new byte[var_data_size];
And last step is to transfer data from binary file by using method

fsBinaryRead.Read(bytData, 0, var_data_size);

At the end, we need to close file stream object.
fsBinaryRead.Close();

Similarly, for binary write in C# it is useful to use SaveFileDialog class. Then we again need FileStream object, let’s say fsBinaryRead

FileStream fsBinaryWrite = File.Create(saveFileDialog1.FileName);

Now, we need to obtain some binary data to be written to binary file.
byte[] bytData = new byte[10];

for(byte i=0; i<10; i++)
{
bytData[i] = i;
}

When binary data are ready, we can write them into binary file:

fsBinaryWrite.Write(bytData, 0, bytData.Length);

At the end, we need to close file stream object.
fsBinaryWrite.Close();

Whole code is:

public partial class Form1 : Form
{

public Form1()
{

InitializeComponent();

}

private void cmdOpen_Click(object sender, EventArgs e)
{

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{

FileStream fsBinaryRead = new FileStream(openFileDialog1.FileName,FileMode.Open);
var var_data_size = (int)fsBinaryRead.Length;
byte[] bytData = new byte[var_data_size];
fsBinaryRead.Read(bytData, 0, var_data_size);
fsBinaryRead.Close();

}

}

private void Form1_Load(object sender, EventArgs e)
{

}

private void cmdSave_Click(object sender, EventArgs e)
{

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{

FileStream fsBinaryWrite = File.Create(saveFileDialog1.FileName);
byte[] bytData = new byte[10];
for (byte i = 0; i < 10; i++)
{

bytData[i] = i;

}
fsBinaryWrite.Write(bytData, 0, bytData.Length);
fsBinaryWrite.Close();

}

}

}

External links:

C Sharp Binary Read and Write on Dotnetperls
C Sharp Binary Read and Write on Microsoft
C Sharp Binary Read and Write on Tutorialspoint

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*