Lesson 20 of 24

In progress

Course progress

C# and .NET

Files and paths

Read and write text, stream large files line by line, and build paths that work on every platform.

System.IO covers most file work in a handful of methods. The bugs come from paths, encodings and unclosed handles, not from the API.

What you will learn

  • Read a whole file and stream a large one.
  • Write text safely, appending or replacing.
  • Build paths with Path.Combine and handle the working directory.

Reading

using System.IO;
string text = File.ReadAllText("data/notes.txt");
string[] lines = File.ReadAllLines("data/orders.csv");
foreach (var line in File.ReadLines("data/orders.csv"))
{
Console.WriteLine(line);
}

ReadAllText and ReadAllLines load the whole file, which is right for configuration and small data. ReadLines is lazy: it yields one line at a time, so a million-line file does not become a million strings in memory.

All three use UTF-8 by default. Pass an Encoding explicitly when reading a file written by something else, or the first non-ASCII character becomes a question mark or a mojibake sequence.

Streaming

using var reader = new StreamReader("data/big.log");
while (reader.ReadLine() is { } line)
{
if (line.Contains("ERROR", StringComparison.Ordinal))
{
Console.WriteLine(line);
}
}

while (reader.ReadLine() is { } line) reads until null in one expression. using var closes the reader at the end of the scope, even if an exception is thrown.

For binary data, use FileStream with Read into a buffer, or File.ReadAllBytes for small files.

Writing

File.WriteAllText("out/report.txt", "done");
File.AppendAllText("out/log.txt", $"{DateTime.UtcNow:O} started{Environment.NewLine}");
File.WriteAllLines("out/rows.csv", new[] { "id,name", "1,Ana" });

WriteAllText replaces the file, creating it if needed. AppendAllText adds to the end, which is what a log wants.

Environment.NewLine is the platform line ending, which matters for text a person will open in Notepad. For data a program will parse, n is usually safer and consistent.

Paths

string path = Path.Combine("data", "2025", "orders.csv");
string full = Path.GetFullPath(path);
Console.WriteLine(Path.GetFileName(path));       // orders.csv
Console.WriteLine(Path.GetDirectoryName(path)); // data/2025
Console.WriteLine(Path.GetExtension(path));     // .csv
Console.WriteLine(Path.ChangeExtension(path, ".bak"));

Path.Combine inserts the right separator for the platform. Never concatenate with / or \ by hand: one of them will be wrong somewhere.

Path.GetFullPath resolves relative paths against the current directory. That directory is the process’s, not the source file’s, which is why a path can work in an IDE and fail from a terminal.

For a path inside the app’s folder, use AppContext.BaseDirectory:

string dataFile = Path.Combine(AppContext.BaseDirectory, "data", "orders.csv");

That is stable whether the app runs from bin/Debug or from a published folder.

Folders

Directory.CreateDirectory("out/2025");
bool exists = Directory.Exists("out/2025");
string[] csv = Directory.GetFiles("out", "*.csv", SearchOption.AllDirectories);
foreach (var file in Directory.EnumerateFiles("out", "*.csv"))
{
Console.WriteLine(file);
}

GetFiles returns an array; EnumerateFiles yields lazily, which matters for a large tree. CreateDirectory succeeds if the folder already exists, so it needs no check.

Safe writes

A crash during WriteAllText can leave a half-written file. For anything important, write to a temporary file and move it into place:

string tmp = path + ".tmp";
File.WriteAllText(tmp, content);
File.Move(tmp, path, overwrite: true);

File.Move with overwrite replaces the target atomically on most platforms, so a reader sees either the old file or the complete new one.

Temporary files

Path.GetTempPath() and Path.GetTempFileName() give you a location for scratch work, and FileOptions.DeleteOnClose removes a file when the handle closes. Both are useful for exports and for tests that need a real file without leaving rubbish behind.

string tmp = Path.Combine(Path.GetTempPath(), $"tin-{Guid.NewGuid():N}.csv");
try
{
File.WriteAllText(tmp, "id,name");
// use it
}
finally
{
File.Delete(tmp);
}

A finally block matters here: an exception between creating and deleting the file otherwise leaves it in the temp folder indefinitely, which is how a machine slowly fills with mystery data.

Errors

  • FileNotFoundException — the path is wrong or the file was removed.
  • DirectoryNotFoundException — a folder in the path does not exist.
  • UnauthorizedAccessException — permissions, or a read-only file.
  • IOException — the file is locked by another process, or the disk is full.

Each has a different cause. Including Path.GetFullPath(path) in your error message is the fastest way to tell a wrong path from a wrong working directory.

CSV, honestly

foreach (var line in File.ReadLines("orders.csv").Skip(1))
{
var parts = line.Split(',');
if (parts.Length < 3) continue;
Console.WriteLine($"{parts[0]} -> {parts[2]}");
}

That handles simple data and fails on quoted fields containing commas. Real CSV needs a library or a proper parser; a hand-written split is fine for a controlled export and wrong for user-supplied files.

Building a path with string concatenation, such as folder + "\" + name. It breaks on Linux and on any path that already ends with a separator. Use Path.Combine.

Write a method that reads a CSV, skips the header, and returns the rows as a list of string arrays, ignoring blank lines.

Show solution
static List<string[]> ReadRows(string path) { var rows = new List<string[]>(); foreach (var line in File.ReadLines(path).Skip(1)) { if (string.IsNullOrWhiteSpace(line)) continue; rows.Add(line.Split(',', StringSplitOptions.TrimEntries)); } return rows; }

ReadLines streams, so the file is never fully in memory. Skip(1) drops the header, and TrimEntries removes spaces around each field, which is the usual annoyance in hand-edited files.

Recap

  • ReadAllText for small files, ReadLines for large ones, using for streams.
  • Path.Combine and AppContext.BaseDirectory make paths portable.
  • Write via a temporary file when a partial write would be harmful.

Next, async and await: keeping a program responsive while it waits.

What is the difference between File and FileInfo?
`File` is a static helper for one-off operations; `FileInfo` caches metadata for repeated access to the same file.
How do I read a file inside a published app?
Put it in the project with `CopyToOutputDirectory` set, then read from `AppContext.BaseDirectory`.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.