C# BinaryWriter TypeUse the BinaryWriter class to write an output file containing integers.
creates binary files. A binary file uses a specific data layout for its bytes. The BinaryWriter type is ideal. It provides a stream-based mechanism for imperatively writing data to a file location on the disk.BinaryReaderFile
Note: Here we see an example of using the BinaryWriter class, which will create the binary file for the example.
BinaryWriter writes data. It is similar to BinaryReader, which reads data. Microsoft states that BinaryReader "reads primitive data types as binary values in a specific encoding." Primitive types are value types like int, uint or char.Int, uintChar
File.Open: In this example, File.Open returns a stream that the BinaryWriter writes through to.
Next: We call Write() to write a value to the file. The Write method is overloaded, which means it handles the exact type you pass it correctly.File.OpenOverload
C# program that uses BinaryWriter
static void Main()
static void W()
// Create 12 integers.
int a = new int
// Use using statement and File.Open.
using (BinaryWriter b = new BinaryWriter(
// Use foreach and write all 12 integers.
foreach (int i in a)
What does the output file look like visually when you inspect it in an editor such as Visual Studio? It is not a great work of art. 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.
Do you need to call the Close method on the BinaryWriter? The using statement will cause the Dispose method to be called. In the Dispose implementation, Close is called. So the answer is no—an explicit Close call is not necessary.Using
Also: If you call BinaryWriter's virtual Close implementation, it calls Dispose. And Dispose then calls the Stream's Close implementation.Stream
Implementation of Dispose: IL
.method family hidebysig newslot virtual
instance void Dispose(bool disposing) cil managed
// Code size 15 (0xf)
IL_0001: brfalse.s IL_000e
IL_0004: ldfld class System.IO.Stream
IL_0009: callvirt instance void System.IO.Stream::Close()
} // end of method BinaryWriter::Dispose
Summary. BinaryWriter provides an efficient and easy way to imperatively construct a binary file. Ideal for certain file formats that your programs must support, the BinaryWriter is used in many projects around the world.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.