Binary Files

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

A binary file is a computer file that is not a text file. The term "binary file" is often used as a term meaning "non-text file". Many binary file formats contain parts that can be interpreted as text Binary files are usually thought of as being a sequence of bytes, which means the binary digits (bits) are grouped in eights. Binary files typically contain bytes that are intended to be interpreted as something other than text characters. Compiled computer programs are typical examples; indeed, compiled applications are sometimes referred to, particularly by programmers, as binaries. But binary files can also mean that they contain images, sounds, compressed versions of other files, etc. — in short, any type of file content whatsoever.

How to use in C#

Writing to binary files:

1 int HighScore = 1000;
2 string name = "Bob";
3 FileStream fsw = new FileStream("High Score.bin", FileMode.Create);
4 BinaryWriter bw = new BinaryWriter(fsw);
5 bw.Write(HighScore);
6 bw.Write(name);
7 fsw.Close();

Any data type can be written to a binary file.

Reading from binary files:

1 int HighScore;
2 string name;
3 FileStream fsr = new FileStream("High Score.bin", FileMode.Open);
4 BinaryReader br = new BinaryReader(fsr);
5 HighScore = br.ReadInt32();
6 name = br.ReadString();
7 fsr.Close();