×

c# · level 2 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A keeps your text after the program ends.

Everything in a variable vanishes when the program ends. A file keeps text on the disk, ready for next time. File lives in the toolbox System.IO, short for input and output, so add using System.IO;.

makes the file, or replaces everything in it if it is already there. gives back the whole file as one string. File.Exists answers True or False.

Read a file that is not there and the program stops with a , so check with File.Exists first, or catch it.

using System;
using System.IO;

File.WriteAllText("note.txt", "Buy milk\nWalk the dog\n");
Console.WriteLine(File.Exists("note.txt"));
Console.Write(File.ReadAllText("note.txt"));
File.WriteAllText("note.txt", "All done!");
Console.WriteLine(File.ReadAllText("note.txt"));
Console.WriteLine(File.Exists("shopping.txt"));

Each run on Gwecode starts with an empty folder, so files only last for that run.