4.2.1.3 - Text and binary files (C#)

4.2.1.3 - Text and binary files (C#)

Read and write persistent data using text and binary files, then choose tests that detect format and boundary errors. This C# route is incomplete: runnable support pending; all source responses here are written practice with no Run.

Fields, records and file organisation

A file keeps data after a program finishes, but its reader must know how that data is organised.

A field holds one value, such as a learner's name or score; a record groups the fields for one learner. In a simple text format, one line might contain Mina,18. The comma separates two fields and the newline separates records. This is a deliberately restricted format: names must not contain commas or newlines. Real CSV permits quoted fields and requires a suitable parser.

Text and binary files

A text file represents content as encoded characters. A binary file stores a defined byte representation that need not be readable as ordinary text. Both ultimately contain bytes.

The integer 18 in a text file is written as the characters 1 and 8. BinaryWriter.Write(18) instead writes the representation of a C# int; BinaryReader.ReadInt32() reads that corresponding four-byte value. A binary format needs agreed types, order and boundaries. Changing a file's extension does not convert its contents.

Text is useful for inspectable reports and exchange with text tools. Typed binary storage avoids converting every number to and from decimal text and can be compact, but an incompatible reader may misinterpret it. Do not assume that every binary format is smaller: headers and representation choices matter.

Text-file reading and writing

Read text a line at a time when each line represents one record, and convert numeric fields explicitly.

This complete program creates scores.txt and then reads it. using disposes each stream even if the block exits exceptionally. The writer closes before the reader opens, so buffered output is available.

C#
using System;
using System.IO;
class Program
{
    static void Main()
    {
        using (StreamWriter writer = new StreamWriter("scores.txt", false))
        {
            writer.WriteLine("Mina,18");
            writer.WriteLine("Omar,12");
        }
        int total = 0;
        using (StreamReader reader = new StreamReader("scores.txt"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] fields = line.Split(',');
                total += int.Parse(fields[1]);
            }
        }
        Console.WriteLine(total);
    }
}

It outputs 30. ReadLine() returns null at end-of-file; it does not return the word null. false in the writer constructor means replace existing contents. Use true to append new lines, understanding that a second run would retain earlier records. The parsing assumes every line has the guaranteed two fields and an integer score. Where that guarantee is absent, check fields.Length and use int.TryParse before accessing or converting a field.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account