Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 182 ยท Standard Library

Files, Paths and Directories

Learn C# file handling - File, Directory and Path classes, reading and writing text, File.ReadLines, FileStream, async I/O, temp files and safe path handling.

Sooner or later a program has to remember something: a settings file, a log, an export, a cache. In C# the everyday tools for that live in System.IO: the static File, Directory and Path classes for quick jobs, FileInfo and DirectoryInfo when you want an object to query, and streams (next lesson) when files get big or you need control.

This lesson covers the common operations from "write a line of text" to "walk a folder tree", then the bigger design questions: how to build paths that work on Windows and Linux, how to avoid half-written files, and how to keep user-supplied names from escaping the folder you meant.

In our editor each run starts in an empty working folder and everything you create disappears when the run ends. That makes the examples safe to repeat, but remember it when you copy code: on your own machine the files are real and permanent. To keep output identical on every run the examples print relative names, not absolute paths.

Writing and reading text

The shortest way to work with a small text file is a single static call. Each call opens the file, does the work and closes it again:

C# WriteAllText and ReadAllText

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Things to know:

  • WriteAllText replaces the file if it exists. AppendAllText adds to the end. Neither fails if the file is missing; both create it.
  • The default encoding is UTF-8 without a byte-order mark. Pass an Encoding as the last argument when you need something else (see Unicode and Encoding).
  • File.Delete on a path that does not exist does nothing; it does not throw. Deleting a missing directory does throw.
  • Reading a missing file throws FileNotFoundException. If its folder is missing too, you get DirectoryNotFoundException.

Reading big files lazily

ReadAllLines loads every line into memory. For a large log that is wasteful. File.ReadLines returns an IEnumerable<string> that reads one line at a time as you iterate, so you can process a multi-gigabyte file in constant memory and stop early:

C# ReadLines is lazy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Careful with one trap: the enumerable keeps the file open until you finish or dispose the enumerator. If you write to the same file while still enumerating it, you get an IOException (the file is in use). Finish reading with .ToList() first, then write.

Paths

A path is just a string, but string concatenation ("data" + "/" + name) breaks on other operating systems and when a piece already ends with a separator. Use Path:

C# The Path class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The separator is / on Linux and macOS and \ on Windows; .NET accepts / on Windows as well, so writing / in literals is portable. Path.Combine and Path.Join choose the right one for you.

Path.Combine("uploads", "/etc/passwd") returns /etc/passwd: an absolute second argument discards the first. Never pass user input to Combine and assume the result stays inside your folder. The "Safe paths" section below shows the fix.

Directories

Directory creates, lists, moves and deletes folders:

C# Working with directories

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Use the Enumerate... methods rather than Get...: they return results lazily, so the first entry appears immediately even in a folder with a million files. The order in which a file system returns entries is not guaranteed, which is why the examples call .Order() before printing.

FileInfo and DirectoryInfo

When you need several facts about one file, create a FileInfo once instead of calling many static methods that each hit the disk:

C# FileInfo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

FileInfo caches its properties; call Refresh() after the file changed outside your object. File.Copy and File.Move refuse to replace an existing target unless you pass overwrite: true.

FileStream: control over bytes

For binary data, partial reads or appending to huge files, open a FileStream. The mode says what to do if the file exists, the access says what you may do, and the share says what others may do while you hold it:

C# FileStream basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The using blocks matter: a stream owns an operating-system handle. If you forget to close it, the file stays locked and buffered data may never be written. Streams get a full lesson next: Streams, Readers and Writers. The using statement itself is explained in IDisposable, using and Finalizers.

Async file I/O

Disk access is slow compared with the CPU. In ASP.NET Core or a UI app, use the async methods so a thread is not blocked while the operating system does the work:

C# Async file methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

All the async methods accept a CancellationToken. See async and await for how the await keyword works.

Temporary files and unique names

For scratch data use the temp folder and let the system pick a unique name, so two runs never collide:

C# Temporary files

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Always delete temp files yourself (a try/finally or a using wrapper) and never use predictable names in a shared folder: another process could create the same name first.

Writing files safely

A crash or power loss while a file is being rewritten leaves it half-written, and the old data is already gone. The standard fix is to write a new file next to the target and then swap it in:

C# Atomic replace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Moving a file within the same volume is atomic on common file systems, so readers see either the old complete file or the new complete file. For long-lived logs, open a FileStream once with FileMode.Append instead of reopening it for every line.

Safe paths: stopping directory traversal

If a user can choose a file name, they can choose ../../secret.txt. This is called path traversal. Resolve the final path with Path.GetFullPath and check that it still starts with your base folder:

C# Blocking path traversal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Use StringComparison.Ordinal (or OrdinalIgnoreCase on case-insensitive systems) for the prefix check, and include the trailing separator in root, otherwise /app/uploads-evil would pass a check against /app/uploads. Better still, generate the stored file name yourself (a GUID) and keep the user's name only as metadata.

Handling errors

File operations fail for reasons outside your control. Catch the specific exceptions:

C# File exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Order the catch blocks from most specific to most general: FileNotFoundException and DirectoryNotFoundException derive from IOException, so they must come first. Instead of checking File.Exists and then opening the file (the file can vanish in between), simply try the operation and handle the exception.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does File.WriteAllText("a.txt", "hi") do when a.txt already exists?

    WriteAllText overwrites. Use AppendAllText to add to the end.
  2. 2. What does Path.Combine("uploads", "/etc/passwd") return?

    An absolute later segment discards everything before it. That is why user-supplied names need a traversal check.
  3. 3. Why prefer File.ReadLines over File.ReadAllLines for a 5 GB log?

    ReadLines streams the file and returns an IEnumerable<string>; ReadAllLines allocates every line at once.
  4. 4. How do you avoid a half-written settings file after a crash?

    Writing a new file and swapping it in means readers see either the old or the new complete file.
  5. 5. Which check blocks ../../secret.txt from escaping an upload folder?

    Normalizing first and then checking the prefix handles every spelling of traversal, not just obvious .. text.

Summary

  • File.ReadAllText, WriteAllText, AppendAllText, ReadAllLines and friends handle small files in one call; ReadLines is lazy for big ones.
  • Build paths with Path.Combine/Path.Join, take them apart with GetFileName, GetExtension and GetDirectoryName.
  • Directory.CreateDirectory, EnumerateFiles and Delete(recursive: true) manage folders; do not rely on enumeration order.
  • FileStream gives byte-level control and must be disposed; async methods keep threads free.
  • Use temp helpers for scratch files and write-then-move for safe saves.
  • Validate user-supplied names with Path.GetFullPath and a prefix check.
  • Catch specific I/O exceptions rather than pre-checking with File.Exists.

Next: Streams, Readers and Writers