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
char in binary to a stream. As its name says
BinaryWriter writes binary files that uses a specific data layout for its bytes.
BinaryWritercreate binary file that is not human understandable but the machine can understand it more smoothly.
- It supports writing string in a specific encoding.
BinaryWriterclass provides methods that simplify writing primitive data types to a stream.
- If you don’t provide types of encoding while creating object then default encoding
UTF-8will 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.
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.
static void Main(string args)
using (BinaryWriter writer = new BinaryWriter(File.Open("D:\\binaryfile.bin", FileMode.Create)))
//Writting Error Log
writer.Write("Windows Explorer Has Stopped Working");
Console.WriteLine("Binary File Created!");
Binary File Created!
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.
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.