Reading and Writing Binary Files in C#

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();
}

Leave a Reply

You must be logged in to post a comment.


All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.