Resource

How to read and write binary data files in C#?

Soft Dev Resources Jul 06, 2009
To read and write binary data files in C#, firstly we creates a new file and data to it.
  • 0
  • 0
  • 80216
This code snippet shows how to create binary data files in C#.

The code first checks if file already exists. If not, creates a new file and add data to it.

using System;

using System.IO;

 

namespace FileOperationsSample

{

    class Program

    {

        static void Main(string[] args)

        {

 

            // Create the new, empty data file.

            string fileName = @"C:\Temp.data";

            if (File.Exists(fileName))

            {

                Console.WriteLine(fileName + " already exists!");

                return;

            }

            FileStream fs = new FileStream(fileName, FileMode.CreateNew);

            // Create the writer for data.

            BinaryWriter w = new BinaryWriter(fs);

            // Write data to Test.data.

            for (int i = 0; i < 11; i++)

            {

                w.Write((int)i);

            }

            w.Close();

            fs.Close();

            // Create the reader for data.

            fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            BinaryReader r = new BinaryReader(fs);

            // Read data from Test.data.

            for (int i = 0; i < 11; i++)

            {

                Console.WriteLine(r.ReadInt32());

            }

            r.Close();

            fs.Close();           

        }

    }

}


COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

TOP RESOURCES

MOST LIKED RESOURCES