SIGN UP MEMBER LOGIN:    
Resource

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

Soft Dev Resources Jul 06, 2009
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();           

        }

    }

}


share this resource :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Sponsored by
Become a Sponsor