Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson15 / 20

    Save and load a small text file

    Your program ends. What could make a note appear again on the next run? Save a small file, then test the first run when it does not exist yet.

    Variables disappear when this console program ends. A file can keep text for a later run. We will use one clearly named practice file, study-notes.txt, in a dedicated practice project folder. The name is relative to the process working directory, usually the folder from which you run the command. It is not automatically relative to Program.cs.

    Predict a save-and-read round trip

    Run this complete program from your practice folder. It writes two lines, reads the file into a string, then prints that string. Write the expected output before running. The backslash-n escape inside the string represents a line break.

    C#
    using System;
    using System.IO;
    
    string path = "study-notes.txt";
    try
    {
        File.WriteAllText(path, "Read variables\nPractise loops");
        string notes = File.ReadAllText(path);
        Console.WriteLine(notes);
    }
    catch (UnauthorizedAccessException)
    {
        Console.WriteLine("The notes location is not writable or readable.");
    }
    catch (IOException)
    {
        Console.WriteLine("The notes could not be saved or read.");
    }

    When both file operations succeed, what prints?

    A Only the file name.
    B Read variables and Practise loops on separate lines.
    C The number of characters in the path.
    D An empty line because the program ended.
    Show answer

    Correct answer: B

    The saved text contains a line break, and ReadAllText returns the text that WriteAllText wrote.

    Option A: The program prints notes, not path.

    Option C: No Length value is printed.

    Option D: The read and print happen before the program ends.

    Hint: Trace the contents string through write, read and print.

    Text
    program string
      "Read variables\nPractise loops"
                | WriteAllText
                v
          study-notes.txt
                | ReadAllText
                v
          notes string --> Console.WriteLine

    WriteAllText creates the file when needed. If the target file already exists, it replaces its contents. Use the practice file for this exercise, and inspect it in your editor after running. Rerunning this same program writes the same two-line content again; it does not append another copy. ReadAllText reads the complete file, so it suits these small notes.

    What does WriteAllText do to an existing study-notes.txt?

    A It appends without changing existing text.
    B It ignores the new text.
    C It replaces the existing contents.
    D It automatically creates a dated backup.
    Show answer

    Correct answer: C

    WriteAllText overwrites the target file’s previous contents.

    Option A: Appending is a separate operation, not this method’s behaviour.

    Option B: The new contents are written when the operation succeeds.

    Option D: This method does not create a backup for you.

    Hint: Consider what happens on the second run.

    Your turn: load without creating a file

    Write a loader that reads an existing study-notes.txt. On a first run with no file, it should print No saved notes yet. A missing file is a situation this loader deliberately handles. Compare your attempt with the complete solution below. To test the missing-file path, run it from a fresh practice folder with no study-notes.txt.

    C#
    using System;
    using System.IO;
    
    string path = "study-notes.txt";
    try
    {
        string notes = File.ReadAllText(path);
        Console.WriteLine($"Saved notes: {notes}");
    }
    catch (FileNotFoundException)
    {
        Console.WriteLine("No saved notes yet.");
    }
    catch (UnauthorizedAccessException)
    {
        Console.WriteLine("The notes cannot be accessed at this location.");
    }
    catch (IOException)
    {
        Console.WriteLine("The notes could not be read.");
    }

    With a file containing exactly Practise methods, expect Saved notes: Practise methods. With an empty file, expect Saved notes: followed by no note text. With no file, expect the missing-file message. Each case tells you something different about the stored state.

    Both File helper methods open and close their file handles for this operation; no manual stream needs to be closed in these examples. The using System.IO; line imports a namespace; it is different from a resource-management using statement. You will meet streams when you need to process larger data gradually.

    Why does this loader catch FileNotFoundException before IOException?

    A More specific handlers should precede a handler for their broader exception type.
    B A file can never become unavailable after a check.
    C The order makes ReadAllText create the file.
    D IOException handles only spelling mistakes.
    Show answer

    Correct answer: A

    FileNotFoundException is a more specific IOException. Putting the specific case first lets the loader give its first-run message.

    Option B: The file system can change; the operation itself still needs appropriate handling.

    Option C: Catch order does not turn a read into a write.

    Option D: IOException represents input/output failures, not source spelling errors.

    Explain it back

    Explain where the relative path is resolved, what a second save does, and why a successful filename check cannot promise a later read will succeed. The catches report failure rather than pretending notes were loaded. Other failures can still surface when a program has no meaningful recovery; this is a small teaching example, not a complete storage system.

    References: Microsoft - File.WriteAllText and File.ReadAllText.

    Quick reference

    • Relative file paths use the process working directory.
    • WriteAllText creates or overwrites a text file.
    • ReadAllText returns the complete text as a string.
    • These File helpers close their handles for the operation.
    • Handle missing files separately when that is a meaningful case.
    • Put a more specific catch before a broader matching type.
    Sign in to mark lessons done and keep your place in the course.Sign in

    TechInterviewNotes Editorial Team · Updated 27 Oct 2026 ·