Until now, your programs have forgotten everything when they stopped. Files fix that. In this browser, files live in memory for a single Run, so an example can write a file and read it back, but it's gone by the next Run. Everything here works the same on your own computer, where the files stay.
Whole files at once
File.WriteAllText creates or replaces a file. File.ReadAllText reads it back as one string, and File.ReadAllLines gives an array of lines. These suit small files well. The File.Exists method and Path.Combine round out the basics, the latter joining folder and file names using the operating system's separator.
File.WriteAllText("note.txt", "first\nsecond\n");
Console.WriteLine(File.Exists("note.txt"));
Console.WriteLine(File.Exists("other.txt"));
string[] lines = File.ReadAllLines("note.txt");
Console.WriteLine(lines.Length);
Console.WriteLine(lines[1]);
File.AppendAllText("note.txt", "third\n");
Console.WriteLine(File.ReadAllText("note.txt").Length);
Directory.CreateDirectory("backup");
string target = Path.Combine("backup", "note.txt");
File.Copy("note.txt", target);
Console.WriteLine(Path.GetFileName(target));
Console.WriteLine(Path.GetExtension(target));Check your prediction
True
False
2
second
19
note.txt
.txtFiles fail
Unlike a list, a file can vanish between two lines of your program. Another program can lock it, and the disk can fill up. So don't rely on checking File.Exists first: the state can change straight after the check. Instead, try the operation and catch the failure. IOException is the base class for most of these, and FileNotFoundException derives from it.
Console.WriteLine(ReadOr("missing.txt", "(none)"));
File.WriteAllText("present.txt", "hello");
Console.WriteLine(ReadOr("present.txt", "(none)"));
static string ReadOr(string path, string fallback)
{
try
{
return File.ReadAllText(path);
}
catch (FileNotFoundException)
{
return fallback;
}
}Check your prediction
(none)
hellousing releases resources
A StreamWriter holds an open file, a resource the garbage collector doesn't release promptly. Types like this implement IDisposable, which has one method: Dispose. A using declaration calls Dispose at the end of the enclosing block, even when an exception is thrown. It's try and finally written for you.
using (var noisy = new Noisy("outer"))
{
using var inner = new Noisy("inner");
Console.WriteLine("working");
}
Console.WriteLine("after");
try
{
using var failing = new Noisy("failing");
throw new InvalidOperationException("boom");
}
catch (InvalidOperationException e)
{
Console.WriteLine(e.Message);
}
class Noisy : IDisposable
{
private readonly string name;
public Noisy(string name)
{
this.name = name;
}
public void Dispose()
{
Console.WriteLine($"disposed {name}");
}
}Check your prediction
working
disposed inner
disposed outer
after
disposed failing
boomResources are released in reverse order, and before the catch runs.
Line by line
ReadAllLines loads a whole file into memory. File.ReadLines returns a lazy sequence, reading only as you loop, so even a huge file is fine, and LINQ can stop early. Note how First below finishes without reading the rest.
using (var writer = new StreamWriter("log.txt"))
{
for (int i = 1; i <= 1000; i++)
{
writer.WriteLine(i % 100 == 0 ? $"ERROR {i}" : $"INFO {i}");
}
}
Console.WriteLine(File.ReadLines("log.txt").First(line => line.StartsWith("ERROR")));
Console.WriteLine(File.ReadLines("log.txt").Count(line => line.StartsWith("ERROR")));Check your prediction
ERROR 100
10Writing goes through a buffer, so the data isn't certain to be in the file until the writer is disposed. That's another reason for using.
Fix it: Written, but not yet
This writes a line and then reads the file back. Predict the output, then run it.
var writer = new StreamWriter("note.txt");
writer.WriteLine("hello");
Console.WriteLine($"[{File.ReadAllText("note.txt").Trim()}]");Check your prediction
[]A StreamWriter collects text in a buffer and writes it to the file in large pieces, and the last piece is written only when the writer is flushed or disposed. Nothing disposed this one, so the file is still empty when it's read. (On Windows you may get an IOException instead, because the undisposed writer still holds the file open. Either way the cause is the same.) Fix it with what this lesson taught.
Fix it
Give the writer a using block, so it's disposed, and its buffer written, before the file is read:
using (var writer = new StreamWriter("note.txt"))
{
writer.WriteLine("hello");
}
Console.WriteLine($"[{File.ReadAllText("note.txt").Trim()}]");[hello]A using var declaration would dispose the writer only at the end of the enclosing block, which here is after the read, so it would print [] again. Use the block form when something later in the same method needs the finished file.
Your turn
A word-count file
Write CountWords(string path), which returns the number of words in a text file using File.ReadLines, or -1 if the file doesn't exist. A word is anything between spaces, and repeated spaces shouldn't create empty words.
Using a StreamWriter, create poem.txt with the lines the quick brown fox and jumps. Then print the count for that file and for nothing.txt.
When it works, it prints:
5
-1Console.WriteLine("Start here");Hint 1: the idea
Try the read and catch the specific failure, rather than checking first. ReadLines reads lazily, but it opens the file straight away, so a missing file throws at the ReadLines call itself: put the call, and the loop over its lines, inside the try.
Hint 2: a first step
Write the file first and print File.ReadAllText to be sure of the contents. Split has an option, StringSplitOptions.RemoveEmptyEntries, for the repeated spaces.
Show one solution
using (var writer = new StreamWriter("poem.txt"))
{
writer.WriteLine("the quick brown fox");
writer.WriteLine("jumps");
}
Console.WriteLine(CountWords("poem.txt"));
Console.WriteLine(CountWords("nothing.txt"));
static int CountWords(string path)
{
try
{
return File.ReadLines(path).Sum(line => line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length);
}
catch (FileNotFoundException)
{
return -1;
}
}5
-1The using block closes the writer before CountWords reads, so the file is complete. File.ReadLines reads one line at a time instead of loading the whole file, and RemoveEmptyEntries stops the double space in "quick brown" counting as an extra word. The method catches only FileNotFoundException, the failure it has an answer for; any other problem, such as a file it isn't allowed to read, still surfaces.
Completion is saved in this browser only. It does not measure mastery.