C# BinaryWriter Class with Programming Examples and Codes

BinaryWriter
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.

    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.


    Leave a Reply

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