How to Create Binary Files

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.
A woman using a computer in a dark room.
Image Credit: demaerre/iStock/Getty Images

A binary file is an encoded text file with the .bin extension. This type of file is used in application programming to save software information without leaving it in plain text. You can save any type of data--strings, integers or booleans--and encode the information. Conversely, you can retrieve this information during software run-time either when the application starts up or as the user interacts with the application.

Advertisement

Step 1

Add the namespace to the code page of your project. Writing and reading files requires the "IO" namespace. A namespace is a library of classes used by a developer. Writing to files requires the classes contained in the IO namespace. Add the following line to the beginning of your code file: include System.IO;

Advertisement

Video of the Day

Step 2

Create the filestream variable and assign it to a binary stream. At this point, the file is created, but it is a blank binary file. Binary files can be created with any extension, but the standard is ".bin." Below is the code that creates the binary file: FileStream file = new FileStream("C:\mybinaryfile.bin", FileMode.Create) GO BinaryWriter binarystream = new BinaryWriter(file);

Advertisement

Step 3

Write to the binary file using the "Write" function. The Write function automatically encodes the values into binary mode, so there is no need to encode the information prior to saving it to the file. Below is an example of writing to a binary file: binarystream.Write("My First Binary File") GO binarystream.Write(10);

Advertisement

Advertisement

Step 4

Close the file once all the information has been saved to the file. Closing the file is important in programming, because the process releases the file and unlocks it for use by users or other applications. The following line closes the binary file and saves it to the hard drive: binarystream.Close();

Video of the Day

Advertisement

Advertisement

references