.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Binary File Read Write Operation In C#

Posted By:Hiren Soni       Posted Date: August 03, 2010    Points: 25    Category: C#    URL: http://www.dotnetspark.com  

Here i will provide you a some code for read and write binary file
 

Subject :

 Read and Write Binary file in c#

 

We can make use of BinaryReader and BinaryWriter class for reading and writing binary files respectively.

 

While creating object of BinaryReader and BinaryWriter we have to pass stream object as constructor argument. First we create the object of FileStream class which references to the specified file. And the object of FileStream class ,we pass as constructor argument of BinaryReader and BinaryWriter class.

 

For  writing in Binary File, the code snippet :-

 

            FileStream fs = new FileStream("c:\\test.bin",FileMode.Create);

            BinaryWriter bw = new BinaryWriter(fs);

            bw.Write(true);  //writing bool value

            bw.Write(Convert.ToByte('a')); //writing byte

            bw.Write('a');                 //writing character

            bw.Write("string");            //string

            bw.Write(123);                 //number

            bw.Write(123.12);              // double value

            bw.Close();

 

 

 

For reading Binary File, the code snippet:-

 

     FileStream fs1 = new FileStream("c:\\test.bin", FileMode.Open);

            BinaryReader br = new BinaryReader(fs1);

            bool b =  br.ReadBoolean();

            byte _byte = br.ReadByte();

            char _char = br.ReadChar();

            string _string = br.ReadString();

            int _int = br.ReadInt16();

            double _dbl = br.ReadDouble();

 

            Console.WriteLine(b);

            Console.WriteLine(_byte);

            Console.WriteLine(_char);

            Console.WriteLine(_string);

            Console.WriteLine(_int);

            Console.WriteLine(_dbl);

            fs1.Close();

 

 

 



 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend