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(Server.MapPath("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();
} |
Okay now lets see what's happening in the code:
- First we made the FileStream object but
in this case we are writing the .dat file which means the data file.
- We created an object of the BinaryWriter
class.
- Later we declared three variables of type int,
decimal and string.
- Finally we wrote the three variables in the
binary file.
If you go and see the file and try to open the
file in notepad you will only see some strange characters. In other words you
won't be able to see the text.
Reading Binary Files :
Lets see how we can read the Binary files.
private void Button1_Click(object sender, System.EventArgs e)
{
FileStream fs = File.OpenRead(Server.MapPath("test.dat"));
BinaryReader br = new BinaryReader(fs);
Response.Write(br.ReadInt32());
Response.Write(br.ReadDecimal());
Response.Write(br.ReadString());
br.Close();
fs.Close();
}
|
As you can see the Reading code for Binary Files
is also very simple. If you have noticed the code is a bit different from which
we saw earlier for reading Text files. Here we are extracting the data types that
we wrote in the binary file. We use ReadInt32() method to read the integer
out from the binary file. We use ReadDecimal() to read the decimal values
from the binary file and so on.
Refer these links for Reading
and Writing Text Files and XML
File operations.