BinaryWriter. This C# type creates binary files. A binary file uses a specific data layout for its bytes. The BinaryWriter type is ideal for creating these files.
Type info. BinaryWriter is a stream-based mechanism for writing data to a file location on the disk. Here we see an example of using the BinaryWriter class, which will create the binary file.
An example. BinaryWriter writes data. It writes primitive types like int, uint or char. In this example, File.Open returns a stream that the BinaryWriter writes through to.
using System.IO;
class Program
{
static void Main()
{
W();
}
static void W()
{
// Create 12 integers.
int[] a = new int[]
{
1,
4,
6,
7,
11,
55,
777,
23,
266,
44,
82,
93
};
// Use using statement and File.Open.
using (BinaryWriter b = new BinaryWriter(File.Open("file.bin", FileMode.Create)))
{
// Use foreach and write all 12 integers.
foreach (int i in a)
{
b.Write(i);
}
}
}
}
Close. The using statement will cause the Dispose method to be called. In the Dispose implementation, Close is called—an explicit Close call is not necessary.
.method family hidebysig newslot virtual
instance void Dispose(bool disposing) cil managed
{
// Code size 15 (0xf)
.maxstack 8
IL_0000: ldarg.1
IL_0001: brfalse.s IL_000e
IL_0003: ldarg.0
IL_0004: ldfld class System.IO.Stream
System.IO.BinaryWriter::OutStream
IL_0009: callvirt instance void System.IO.Stream::Close()
IL_000e: ret
} // end of method BinaryWriter::Dispose
File data. What does the output file look like visually when you inspect it in an editor such as Visual Studio? It is not something easily read—it looks like random bytes.
And This is because the data is not encoded as a text file but instead a more efficient, machine-level representation of numeric data.
Tip Don't worry—the file can still be treated as a series of numbers. Buy we must use a program to read it.
Summary. BinaryWriter is an easy way to create a binary file. Ideal for certain file formats that your programs must support, the BinaryWriter is used in many projects around the world.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 22, 2022 (edit).