Drop links or images here to add them to the editor.

Reading and writing to text files.

Saving data

Try

Watch this video to learn about the new concepts shown in the program:

Knowledge organiser

The new commands used in this program and others that may be useful. Select them below to learn more:

StreamReader x = new StreamReader(y);

x is a pointer to the file y. This command is used to open a file for reading. The file must already exist otherwise the program will crash.

Note that a file can only be open for either reading (using a StreamReader) or writing (using a StreamWriter) at any one time. You must make sure the System.IO namespace is included in your program before attempting to open a file: using System.IO;

StreamWriter x = new StreamWriter(y, z);

x is a pointer to the file y with the data flow z. The data flow can be:

  • true appends data to the end of the file
  • false overwrites existing data in the file

If the parameter z is not specified existing data will be over-written. If the file does not already exist, then it will be created when the StreamWriter is assigned.

Note that a file can only be open for either reading (using a StreamReader) or writing (using a StreamWriter) at any one time. You must make sure the System.IO namespace is included in your program before attempting to open a file: using System.IO;

string x = y.ReadLine();

x is assigned to one line of data from an open file y. Note data may include character codes, for example end of line characters. Use the .Trim() method to remove invisible character codes from the data read from a file.

string x = y.ReadToEnd();

x is assigned to all the data from an open file y. Note data may include character codes, for example end of line characters. Use the .Trim() method to remove invisible character codes from the data read from a file.

x.WriteLine(y);

Writes a new line of data y to an open file x.

x.Write(y);

Writes data y to an open file x. Data is appended without a new line.

x.Close();

Close the file pointer x. File should be closed as soon as possible. Not closing files can in some cases corrupt the file.

Investigate

Questions to think about with this program to check your understanding:

Item question

Identify a new line character in the program.

Reveal answer

\n is a new line character. Also called a line feed or end of line marker. It is an example of what is known as an “escape code”. These are signals to a device to execute a text command rather than print or display the text characters.

Structure question

Explain the difference between StreamReader and StreamWriter.

Reveal answer

StreamReader reads from a file.

StreamWriter overwrites or writes to a file.

Make

Change the program so that:

  1. If a user has been stored in the file it outputs, “It’s good to see you again,” followed by the first line of data in the file.
  2. If the datafile.txt is empty it outputs, “Hello, I don’t believe we have met.”, asks the user for their name, saves this to datafile.txt and welcomes them with “Nice to meet you <name>.”.

Typical inputs and outputs from the program would be:

Hello, I don't believe we have met.
What is your name?
Dave
Nice to meet you Dave.
It's good to see you again, Dave.
🆘 If you're really stuck, use this Parsons code sorting exercise
Complete program
// Saving data program

using System;
using System.IO;

class Submission
{
---
    // -------------------------
    // Subprograms
    // -------------------------
    // Load a single line of data
---
    static string load(string filename)
    {
---
        StreamReader file = new StreamReader(filename);
        string user = (file.ReadLine() ?? "").Trim();
        file.Close();
        return user;
---
    }
---


    // Save a single line of data
    static void save(string user, string filename)
    {
---
        StreamWriter file = new StreamWriter(filename);
        file.WriteLine(user);
        file.Close();
---
    }
---


    // -------------------------
    // Main program
    // -------------------------
    public static void Main(string[] args)
    {
---
        string user = load("datafile.txt");
---
        // If the file is empty, ask for the data to save...
        if (user == "")
        {
---
            Console.WriteLine("Hello, I don't believe we have met.");
            Console.WriteLine("What is your name?");
            user = Console.ReadLine();
---
            save(user, "datafile.txt");
            Console.WriteLine($"Nice to meet you {user}.");
---
        }
---
        else
        {
---
            // ...otherwise display the data in the file
            Console.WriteLine($"It's good to see you again, {user}.");
---
        }
---
    }
---
}