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

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

        }

    }

}