C# BinaryWriter Class with Programming Examples and Codes

In this chapter you will learn:
  • What is BinaryWriter Class?
  • How to Write Binary File?
  • Programming Examples and Codes

What is BinaryWriter class?

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

Notes:

  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.
 

How to write Binary Files?

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

Output: Binary File Created! binary

When you open the file D:\binaryfile.bin in visual studio the file may look like this. However, it is hard to understand but it is more efficient and machine level representation of data. This is because the data is not encoded in text file. Don't worry when you read your data using BinaryReader Class you will get exact data that you saved.

Summary

In this chapter you have learned BinaryWriter class and its implementation in programming. In the next chapter you will learn BinaryReader class in C# with complete programming examples and codes.

 

Share your thought