CodeGym /Courses /C# SELF /File Formats: Text and Binary

File Formats: Text and Binary

C# SELF
Level 35, Lesson 1
Available

1. Text Files

Remember: a computer stores everything, literally everything, as ones and zeros (or, if you’re not afraid of scary words — as a sequence of bytes). But if you feed the same file to two different programs, there’s no guarantee they’ll react to it the same way. One program might see regular text, while another sees a bunch of “broken bytes.” It’s all about the file format — how exactly those bytes are interpreted. The format describes the internal data structure, the rules for reading it, and the encoding. Without knowing the format, a program might have no clue what’s actually stored in the file.

A text file is a file where the data is just regular text in some encoding (usually UTF-8, or if you’re feeling hardcore — ASCII). You can open this kind of file in any text editor (like Notepad or VS Code) and read it right away — it’s just lines of characters, not mysterious control bytes or binary structures.

Typical Examples

  • *.txt — regular text files, like "to-do.txt" or "best-books.txt".
  • *.csv — files where data is separated by commas or semicolons (great for tables).
  • *.json — files for exchanging structured data (like book lists).
  • *.xml,*.html — for storing and transferring structured data.

CSV File Example


Dune;Frank Herbert;1965
1984;George Orwell;1949
The Master and Margarita;Mikhail Bulgakov;1966
Example contents of books.txt (CSV format)

Each line is a separate record (like a book). The values in a line are separated by a semicolon, which makes the file a CSV (Comma-Separated Values) example. Comma is supposed to be a comma, but here it’s swapped for another separator (;). The characters you see are the same bytes the program reads, as long as it knows how to interpret the text format and file encoding.

How a Program Works with a Text File

Just open the file “as text” and you can read it line by line. Here’s an example (which will come in handy in future lectures):


// Simple line-by-line reading from a file (we’ll break down the details soon)
string[] lines = File.ReadAllLines("books.txt");
foreach (string line in lines)
{
    Console.WriteLine(line);
}

Advantages of Text Files

  • Human-readable.
  • Easy to edit by hand (even in the simplest app like Notepad).
  • Great for debugging and exchanging between different systems.
  • Easy to move between platforms (Windows, Linux, Mac).

Disadvantages of Text Files

  • No strict structure (txt), formatting errors are easy to make by accident.
  • Take up more space (for example, the number 12345 = 5 bytes, but in binary — 4).
  • Complex data (like images, audio) is awkward or impossible to transfer as text.
  • Performance: slower for large amounts of data.

Good to Know

  • Different platforms see “end of line” differently: Windows — \r\n, Unix — \n.
  • Encodings can differ (UTF-8, UTF-16, ANSI, etc.), so a file written on one system might show up as “Chinese hieroglyphs” on another (it’s just the wrong interpretation of bytes).

2. Binary Files

A binary file is a file where the contents are not characters, but arbitrary bytes. They can mean anything: numbers, structures, images, music, even machine code. Try opening a .exe in Notepad — you’ll see a bunch of weird gibberish!

Typical Examples

  • *.exe, *.dll — executable files and libraries.
  • *.jpg, *.png, *.gif— images.
  • *.mp3, *.wav— audio files.
  • *.dat — files with arbitrary user data.
  • App-specific formats (*.docx, *.xlsx, etc.) — almost always binary.

How is a Binary File Structured?

Byte by byte, the program writes and reads data in whatever format it needs. For example, an int gets written as 4 bytes (32 bits), and a string is usually length + the character bytes in a certain encoding.

In a text file, the number 12345 is the bytes for the characters '1', '2', '3', '4', '5':

Character UTF-8 Code
1 49
2 50
3 51
4 52
5 53

In a binary file, int 12345 (little-endian) looks like this:

Position Byte (hex) Value
0 0x39 57
1 0x30 48
2 0x00 0
3 0x00 0

(In other words: 12345 = 0x00003039.)

Try writing the same number as text and as binary — and compare the file sizes. The binary one will be a bit smaller.

How a Program Works with a Binary File

Special streams (like BinaryReader, BinaryWriter). Unlike a text file, you have to know the structure exactly, or you won’t be able to read the data.


// Example: writing numbers to a binary file
var writer = new BinaryWriter(File.Open("books.bin", FileMode.Create));

// Say we’re writing encoding: number of characters (int), then the bytes
string title = "Dune";
writer.Write(title.Length); // Write length (int)
writer.Write(title); // Write string (will be in UTF-8)
writer.Write(1965); // Write year (int)

writer.Close(); // close the stream

This is just an example. I’ll tell you more about working with binary files in upcoming lectures.

Advantages of Binary Files

  • Compact: take up less space.
  • Faster to read and write (especially for big data sets).
  • You can store complex structures: arrays, nested objects, etc.

Disadvantages of Binary Files

  • Not human-readable.
  • If the file structure changes, old data might be lost or “break.”
  • You always need exact instructions to parse the contents.

3. Which Format Should You Choose?

Text vs Binary Files

Criteria Text File Binary File
Human-readable Yes No
Size Bigger Smaller
Universality High (any editor) Only special programs
Speed Slower Faster
Strict format No Yes, must follow
Storing structures Hard Easy
Risk of data corruption Low (easy to edit) High (even a tiny glitch — file unreadable)

How to Choose

  • Need the data to be human-readable, easy to change and debug? — Use a text file (like .txt, .csv, .json).
  • Data is complex, size and speed matter? — Go binary.
  • Need to exchange data between different platforms? — Text is better, but use a standard encoding (UTF-8).
  • App will read and write a lot of data, and the format is strict? — Pick binary.

In our console app “Book List” at first, a text format (.csv or .txt) is perfect. Later, when the structure gets more complex or you want faster loading, you can check out binary files or switch to JSON/XML.

4. Handy Details

Where do you see text and binary files in real life?

Text files:

  • App settings (often in .ini or .json).
  • Scripts, logs, notes.
  • Import/export files (data for exchanging between apps).

Binary files:

  • Programs, games, libraries (nobody just peeks inside).
  • Big databases and archives (like .mdb, .zip).
  • Media: music, photos, video.

Reading the Whole File at Once (as text):


string allText = File.ReadAllText("books.txt");
// Now allText is a giant string with all the contents

Line by Line (best for lists):


string[] lines = File.ReadAllLines("books.txt");
foreach (string line in lines)
{
    // You can split the line into parts
    string[] parts = line.Split(';');
    // parts[0] — title, parts[1] — author, parts[2] — year
}

Binary Reading — Stick to the Structure


var reader = new BinaryReader(File.Open("books.bin", FileMode.Open));

int count = reader.ReadInt32(); // How many books
for (int i = 0; i < count; i++)
{
    string title = reader.ReadString();
    string author = reader.ReadString();
    int year = reader.ReadInt32();
    // Now you can restore the record!
}

reader.Close();

5. Practical Example: Creating a File with Books

Saving Data to a Text File

We’ll store each book in a line like this:
title;author;year of first edition


// List of books we want to save
var books = new List<(string Title, string Author, int Year)>
{
    ("Dune", "Frank Herbert", 1965),
    ("1984", "George Orwell", 1949),
    ("The Master and Margarita", "Mikhail Bulgakov", 1966)
};

// Save to a text file
var writer = new StreamWriter("books.txt");
foreach (var book in books)
    writer.WriteLine($"{book.Title};{book.Author};{book.Year}");

writer.Close();

You can open books.txt in Notepad and see all the data.

Storing Data in a Binary File

Now let’s try the same thing, but more compact (though not human-readable):


var writer = new BinaryWriter(File.Open("books.bin", FileMode.Create));

writer.Write(books.Count); // Write the number of books
foreach (var book in books)
{
    writer.Write(book.Title); // String - stored as: length + bytes
    writer.Write(book.Author); // String
    writer.Write(book.Year); // Year (int)
}

writer.Close();

If you try to open books.bin in a text editor, you’ll see chaos: a bunch of unreadable symbols. That’s normal. Binary files aren’t meant for humans — only a program that knows exactly how the file was written can handle them right.

6. Common Mistakes When Working with Formats

If you try to read a binary file as text, you’ll get a “mess” of symbols or even an error. Likewise, if you open a text file as binary and expect a strict structure — you’ll have problems.

The most common mistake: mismatch between the data structure and the order of reading/writing. For example, you write the year first, then the title, but read them in the opposite order — you’ll get the wrong info. Always stick to the same order of operations!

A lot of programmers “peek” into a text file to check their save/load logic — that’s exactly why text formats are so handy for your first steps. Binary is for more advanced scenarios, or when you want to hide storage details from the user.

2
Task
C# SELF, level 35, lesson 1
Locked
Writing and Reading a Text File
Writing and Reading a Text File
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION