0.4.16 Writing Information to a Text File

Writing Makes Runtime Information Persistent

Suppose a soccer application contains a lineup note:

string lineupNote = "Jordan starts at forward.";

At this moment, the value belongs to the running program.

To preserve it after the program closes, the application can write the text to a file.

A simple C# API for this purpose is:

System.IO.File.WriteAllText
A Simple Write

An instructional example is:

string lineupNote = "Jordan starts at forward.";

System.IO.File.WriteAllText("lineup.txt", lineupNote);

Read the second statement as:

The first argument identifies the file.

The second argument provides the text to write.

The File Receives a Text Representation

After the write, the file contains:

Activity diagram showing Create or gather information, then Create the text to store, then Write the text to the file.
CreateOrGatherInformation.
  • New
  • Changed
  • Removed
Writing Is an Action, Not a Permanent Connection

After writing:

System.IO.File.WriteAllText("lineup.txt", lineupNote);

the file does not remain automatically synchronized with the variable.

If the program later changes:

lineupNote = "Casey starts at goalkeeper.";

the file still contains the earlier text until another write occurs.

A write captures the text supplied at the time of the operation.

A Useful Storage Flow

Conceptually:

Activity diagram showing lineupNote in memory, then File.WriteAllText(...), then lineup.txt on persistent storage.
LineupNoteInMemory.
  • New
  • Changed
  • Removed

The code implements the write action you previously modeled with an activity diagram.

Saving Is Different From Displaying

A program can display:

Jordan starts at forward.

without writing a file.

It can also write that text to a file without showing the text on screen.

Display and persistence are different responsibilities.

Do not assume visible output has automatically been saved.

Keep File Writing Introductory

For this module, focus on one simple idea:

System.IO.File.WriteAllText(path, text);

The program has text in memory.

The method writes that text to persistent storage.

Later courses can add:

  • more complex paths;
  • multiple records;
  • structured formats;
  • streams;
  • exception handling;
  • databases.

Those are not needed to understand the basic movement of information from memory to a text file.