BinaryWriter class writes Primitive type data type as intuint or char in binary to a stream. As its name says BinaryWriter writes binary files that uses a specific data layout for its bytes.

  1. BinaryWriter create binary file that is not human understandable but the machine can understand it more smoothly.
  2. It supports writing string in a specific encoding.
  3. BinaryWriter class provides methods that simplify writing primitive data types to a stream.
  4. If you don’t provide types of encoding while creating object then default encoding UTF-8 will be used.

BinaryWriter class makes easy to write Binary File in C#. It gives us great number of useful methods that makes Binary operation easier. You’ll get more clear clarification by looking the given program.

PROGRAMMING EXAMPLE:

Here, I am writing a program explaining BinaryWriter class. This program creates a new binary file at location “D:\binaryfile.bin” and then stores error log information in it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace BinaryWriter_Class
{
    class Program
    {
        static void Main(string[] args)
        {            
            using (BinaryWriter writer = new BinaryWriter(File.Open("D:\\binaryfile.bin", FileMode.Create)))
            {
                //Writting Error Log
                writer.Write("0x80234400");
                writer.Write("Windows Explorer Has Stopped Working");                
                writer.Write(true);
            }
            Console.WriteLine("Binary File Created!");
            Console.ReadKey();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *