Reading and Writing Binary Files in C#
Writing Binary Files :
For files with known internal structures, the BinaryReader and BinaryWriter classes offer streaming functionality that’s oriented towards particular data types. The good thing about writing binary files are you cannot read the files by just opening them in the notepad also binary files can be of very large size. Lets look at the code to create Binary files.
private void Button1_Click(object sender, System.EventArgs e)
{
FileStream fs = File.Create(”C:\\test.dat”);
BinaryWriter bw = new BinaryWriter(fs);
int x = 10;
decimal d = 3.234M;
string str = “Hello World”;
bw.Write(x);
bw.Write(d);
bw.Write(str);
bw.Close();
fs.Close();
}
Reading Binary Files :
private void Button1_Click(object sender, System.EventArgs e)
{
FileStream fs = File.OpenRead(”C:\\test.dat”);
BinaryReader br = new BinaryReader(fs);
Response.Write(br.ReadInt32());
Response.Write(br.ReadDecimal());
Response.Write(br.ReadString());
br.Close();
fs.Close();
}
