c# · level 2 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
The score is saved twice. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.IO;
File.WriteAllText("score.txt", "10");
File.WriteAllText("score.txt", "25");
string text = File.ReadAllText("score.txt");
Console.WriteLine(text + text);
your turn
Your turn. Keep a diary.
Gwecode types went swimming. Choose a file name on line 5, then on line 6 read the whole of that same file back. Press run.
output
press run to see what happens
fix it
The high score went missing. Fix it!
output
press run to see what happens
- C# stops with
FileNotFoundExceptionon line 5. Compare the file name there with the one on line 4. - The file was saved as
highscore.txt, with no s on the end. - Change
highscores.txttohighscore.txton line 5, then press run.
nailed it
your text outlives the program. :D
File.WriteAllTextsaves, replacing what was there.File.ReadAllTextreads the whole file back.- Missing files give
FileNotFoundException.
new words in your collection
- file
- File.WriteAllText
- File.ReadAllText
- FileNotFoundException
This lesson isn’t saved. A free account remembers every lesson you finish.