← C# from Scratch Lesson 37 of 39 · 10 XP

Files

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

The File class from System.IO reads and writes a whole file in a single call:

using System.IO;

File.WriteAllText("save.txt", "level=3\n");       // create / overwrite
File.AppendAllText("save.txt", "hp=80\n");        // append to the end
string all = File.ReadAllText("save.txt");        // the whole file as a string
string[] lines = File.ReadAllLines("save.txt");   // line by line
File.WriteAllLines("list.txt", new[] { "a", "b" });
bool ok = File.Exists("save.txt");
File.Delete("save.txt");

For big files — line by line, through a stream:

using (var w = new StreamWriter("log.txt"))       // using closes the file even if an error happens
{
    w.WriteLine("start");
}
foreach (string line in File.ReadLines("log.txt"))  // reads lazily, not the whole file into memory
    Console.WriteLine(line);

Relative paths are resolved from the program's current working directory. Path.Combine("saves", "slot1.txt") builds a path correctly on both Windows (\) and Linux (/).

Task. Read the input lines to the end and write only the non-empty ones to the file notes.txt, each with a number (1. text). Then read the file back and print its contents, with lines: N as the last line.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.