Files and directories

The .NET base class library reads and writes files through the static File and Directory classes, and through FileInfo and DirectoryInfo when a program asks about one entry more than once. Everything in this lesson is synchronous, which is fine for a command-line tool; a service uses the ...Async variants shown in the lesson on async and await.

Writing and reading a file

File.WriteAllText creates the file or replaces its contents, and File.ReadAllText returns the whole file as one string. The program builds a folder under Path.GetTempPath() so that it never writes into the folder it was started from:

var dir = Path.Combine(Path.GetTempPath(), "aredel-csharp-files"); if (Directory.Exists(dir)) { Directory.Delete(dir, true); } Directory.CreateDirectory(dir); var path = Path.Combine(dir, "notes.txt"); File.WriteAllText(path, "first\nsecond\n"); Console.WriteLine($"exists {File.Exists(path)}"); Console.WriteLine($"text [{File.ReadAllText(path).Replace("\n", "|")}]"); Console.WriteLine($"lines {File.ReadAllLines(path).Length}"); var info = new FileInfo(path); Console.WriteLine($"length {info.Length}"); Console.WriteLine($"name {info.Name}"); Console.WriteLine($"modified {info.LastWriteTimeUtc.Year >= 2024}"); Console.WriteLine($"folder {Directory.Exists(dir)}");

dotnet run

exists True
text [first|second|]
lines 2
length 13
name notes.txt
modified True
folder True

Thirteen bytes is the text itself: five for first, six for second and two line breaks. ReadAllLines splits on the line breaks and returns an array, and FileInfo answers the questions about one file without opening it. The encoding of WriteAllText is UTF-8 without a byte order mark, which the next lesson measures on the bytes.

A folder of files

Directory.GetFiles returns the full paths of the files of one folder and does not descend into its subfolders; GetDirectories returns the folders. Neither promises an order, so the program sorts before it prints:

var dir = Path.Combine(Path.GetTempPath(), "aredel-csharp-list"); if (Directory.Exists(dir)) { Directory.Delete(dir, true); } Directory.CreateDirectory(dir); Directory.CreateDirectory(Path.Combine(dir, "archive")); File.WriteAllText(Path.Combine(dir, "b.log"), "log\n"); File.WriteAllText(Path.Combine(dir, "a.txt"), "text\n"); File.WriteAllText(Path.Combine(dir, "archive", "old.txt"), "old\n"); foreach (var file in Directory.GetFiles(dir).Order()) { Console.WriteLine($"file {Path.GetFileName(file)}"); } foreach (var folder in Directory.GetDirectories(dir)) { Console.WriteLine($"dir {Path.GetFileName(folder)}"); } File.AppendAllText(Path.Combine(dir, "a.txt"), "more\n"); Console.WriteLine($"appended [{File.ReadAllText(Path.Combine(dir, "a.txt")).Replace("\n", "|")}]"); File.Move(Path.Combine(dir, "b.log"), Path.Combine(dir, "b.old.log")); File.Delete(Path.Combine(dir, "b.old.log")); Console.WriteLine($"left {Directory.GetFiles(dir).Length}"); Directory.Delete(dir, true); Console.WriteLine($"gone {!Directory.Exists(dir)}");

dotnet run

file a.txt
file b.log
dir archive
appended [text|more|]
left 1
gone True

The listing shows the two files of the folder and the one folder, without the file inside archive. AppendAllText adds to the end instead of replacing, File.Move renames within the same folder and File.Delete removes one file; a delete of a file that is not there does not throw, unlike a read. Directory.Delete(dir, true) removes the folder with everything under it.

A file that is not there

Reading a file that does not exist throws FileNotFoundException, which is an IOException and therefore a SystemException. The message carries the path the program asked for:

var path = Path.Combine(Path.GetTempPath(), "aredel-missing.txt"); if (File.Exists(path)) { File.Delete(path); } try { File.ReadAllText(path); } catch (FileNotFoundException e) { Console.WriteLine($"caught {e.GetType().Name}"); Console.WriteLine($"message {e.Message}"); } Console.WriteLine($"safe {File.Exists(path)}");

dotnet run

caught FileNotFoundException
message Could not find file '/tmp/aredel-missing.txt'.
safe False

File.Exists answers false for a missing file and never throws, so it is the cheap guard before a read. It answers false for a folder too, because a folder is not a file. The exception type is the one to catch when the missing file is a real error; when it is an expected case, as in a configuration lookup, Exists is the shorter form.

Temporary files

Every program of this lesson writes under Path.GetTempPath(), which is /tmp/ here and the user temp folder on Windows. A program that writes into its own folder leaves files in the source tree, which then show up in git status and in a published package. A temporary file is the right place for a file whose contents do not matter after the program ends, and the program should still delete it: /tmp is cleaned by the system, but not when a container is killed.

The lesson on paths goes into Path.Combine, GetFileName and the rest of the path API, and the next lesson opens the same files through a stream instead of reading them whole.

Exercises

  1. Write a file with ten numbered lines and read it back with ReadAllLines; print the fifth.
  2. Count the files of the temporary folder with Directory.GetFiles and print the count.
  3. Call File.Move with a target that already exists and read the exception.
  4. Write a file with Encoding.Latin1 and compare its length with the UTF-8 one for the same text.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which call writes a string to a file, creating it when it does not exist?

    Answer

    File.WriteAllText

    WriteAllText creates the file or replaces its contents with the string.

  2. What does File.ReadAllLines return?

    Answer

    An array of strings, one per line

    It splits the text on the line breaks and returns string[].

  3. What does this program print? Console.WriteLine(File.Exists("/tmp"));

    Answer

    False

    File.Exists is about files only and answers false for a directory.

  4. What does this program print? var path = Path.Combine(Path.GetTempPath(), "q.txt"); File.WriteAllText(path, "abc"); Console.WriteLine(new FileInfo(path).Length); File.Delete(path);

    Answer

    3

    Three ASCII characters are three bytes, and UTF-8 adds no byte order mark here.

  5. Which exception does File.ReadAllText throw for a missing file?

    Answer

    FileNotFoundException

    The file is not there, which is what FileNotFoundException reports.

  6. In which order does Directory.GetFiles return the files?

    Answer

    No order is promised

    The order is a detail of the file system, so the program sorts when it matters.

  7. What does this program print? Console.WriteLine(Path.GetFileName("/srv/app/report.csv"));

    Answer

    report.csv

    GetFileName returns the last part of a path.

  8. Which call adds text to the end of a file that already exists?

    Answer

    File.AppendAllText

    AppendAllText keeps the old contents and writes after them.

  9. What does Directory.Delete(dir, true) do?

    Answer

    Deletes the folder and everything under it

    The boolean is the recursive flag, and the program printed gone True.

  10. What does this program print? var path = Path.Combine(Path.GetTempPath(), "e.txt"); if (File.Exists(path)) { File.Delete(path); } Console.WriteLine(File.Exists(path));

    Answer

    False

    The file was never created, and File.Exists reports that without throwing.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev