File I/O: The Filing Cabinet

File I/O: The Filing Cabinet in C#: A filing cabinet offers two ways to work. You can pull the entire drawer onto your desk, spread every folder out, and see…

The Analogy: Whole Drawer or One Page at a Time

A filing cabinet offers two ways to work. You can pull the entire drawer onto your desk, spread every folder out, and see the lot at once — fast, obvious, and fine until the drawer holds ten thousand pages and your desk is the size of a laptop. Or you can stand at the cabinet and read one page at a time, putting each back before taking the next. Slower per page, but the desk never overflows.

That is precisely the choice the File class puts in front of you. File.ReadAllLines is the whole drawer: every line in a string[], indexable, sortable, countable — and entirely in memory. File.ReadLines is the page-at-a-time approach: it hands you one line, then reads the next only when you ask. On a 20-line config file the difference is invisible. On a 4 GB log file, one of them works and the other throws OutOfMemoryException.

The rest of file work is bookkeeping, and it is where the real bugs live: building paths without hard-coded backslashes, creating a folder before writing into it, not trusting File.Exists as a guarantee, and never leaving a half-written file where a reader can find it. Get those four habits right and file handling stops being a source of 2 a.m. phone calls.


Syntax or Core Structure

Everything here lives in System.IO. File and Directory are static helpers for one-shot operations; Path builds and dissects path strings without ever touching the disk.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // Build paths with Path.Combine - never by gluing on a separator.
        string folder = Path.Combine("data", "day1");
        Directory.CreateDirectory(folder);            // silently OK if it exists

        string file = Path.Combine(folder, "readings.txt");

        // Whole-file writes REPLACE the file; append adds to the end.
        File.WriteAllLines(file, new[] { "12", "7", "3" });
        File.AppendAllText(file, "40" + Environment.NewLine);

        Console.WriteLine("exists: " + File.Exists(file));
        Console.WriteLine("lines:  " + File.ReadAllLines(file).Length);

        // ReadLines streams: one line in memory at a time, whatever the size.
        int total = 0;
        foreach (string line in File.ReadLines(file))
            total += int.Parse(line);
        Console.WriteLine("total:  " + total);

        // Path only manipulates text; it never checks the disk.
        Console.WriteLine("name:   " + Path.GetFileName(file));
        Console.WriteLine("ext:    " + Path.GetExtension(file));
        Console.WriteLine("base:   " + Path.GetFileNameWithoutExtension(file));

        string copy = Path.Combine(folder, "backup.txt");
        File.Copy(file, copy, overwrite: true);

        string[] found = Directory.GetFiles(folder, "*.txt");
        Array.Sort(found);                            // order is NOT guaranteed
        foreach (string path in found)
            Console.WriteLine("found:  " + Path.GetFileName(path));

        File.Delete(copy);
        Console.WriteLine("after delete: " + Directory.GetFiles(folder).Length + " file");
    }
}

Output:

exists: True
lines:  4
total:  62
name:   readings.txt
ext:    .txt
base:   readings
found:  backup.txt
found:  readings.txt
after delete: 1 file

Array.Sort is not decoration. Neither GetFiles nor EnumerateFiles promises any particular order — it is whatever the file system hands back — so any code that depends on alphabetical or chronological order has to say so explicitly.


Technical Depth: Choosing the Right Call

The File class has two families, and the difference is memory, not speed:

CallReturnsMemoryUse when
File.ReadAllTextstringWhole fileConfig, JSON, small documents
File.ReadAllLinesstring[]Whole fileYou need indexing, sorting, Length
File.ReadLinesIEnumerable<string>One lineLogs, exports, anything unbounded
File.WriteAllText-Whole stringReplacing a small file
File.AppendAllText-Just the additionAdding to a log
new StreamReader(path)A readerOne bufferCustom parsing, encodings, Peek
File.OpenReadFileStreamOne bufferBinary data, seeking

ReadLines is lazy: nothing is read until you start the foreach, and the file handle stays open for as long as you are enumerating. That is why you should not start a ReadLines loop and then try to delete the file inside it.

The path rules that survive both Windows and Linux

Path.Combine("data", "day1", "a.txt")   // data\day1\a.txt or data/day1/a.txt
Path.GetFullPath("a.txt")               // resolves against the current directory
Path.DirectorySeparatorChar             // '\' on Windows, '/' on Linux
Path.GetTempPath()                      // the OS temp folder, with separator

Three rules follow from that. Never write folder + "\\" + name — it breaks on Linux and produces doubled separators on Windows. Never assume the working directory: Environment.CurrentDirectory is wherever the process was launched from, while AppContext.BaseDirectory is where your assembly lives, and they are different in a service. And remember that Linux file names are case-sensitive, so Readings.txt and readings.txt are two files there and one file on Windows — a bug that only ever appears after deployment.

File.Exists is a rumour, not a contract

if (File.Exists(path))          // true...
    File.Delete(path);          // ...and by now another process deleted it

Between those two lines, anything can happen: another process, another thread, an antivirus scanner, a network share going away. This is the classic time-of-check-to-time-of-use race. The reliable pattern is to attempt the operation and handle the failure:

try
{
    string text = File.ReadAllText(path);
}
catch (FileNotFoundException)  { /* it is not there  */ }
catch (DirectoryNotFoundException) { /* folder went  */ }
catch (UnauthorizedAccessException) { /* no rights   */ }
catch (IOException)            { /* locked, or gone */ }

Use File.Exists for user-facing questions ("is there a config file to offer?"), not as protection.

Half-written files, and how to never publish one

If your process dies mid-write, readers find a truncated file. The fix is to write somewhere else and then move, because a move within one volume is atomic:

string temp = target + ".tmp";
File.WriteAllText(temp, content);
File.Move(temp, target, overwrite: true);   // readers see old OR new, never half

File.Replace goes one step further and can keep a backup of what was there. What you must not do is File.WriteAllText(target, ...) on a file other code is reading.

Encoding and async, briefly

Modern .NET writes UTF-8 without a byte-order mark by default and detects a BOM when reading, which is why round-tripping through File.WriteAllText/ReadAllText just works. Pass an Encoding explicitly only when another system demands it. And every one of these methods has an async twin — ReadAllTextAsync, WriteAllLinesAsync, and IAsyncEnumerable<string> from File.ReadLinesAsync — which is what you want in a web request, where blocking a thread pool thread on a disk is the difference between 200 and 20 requests a second.


Real World Example: An Inbox Processor

Files arrive in an inbox folder. Valid ones move to processed, invalid ones to failed, anything that is not a .csv is left alone, and a summary is published atomically at the end. This is the skeleton of a hundred real integration jobs.

using System;
using System.Globalization;
using System.IO;

class Program
{
    static void Main()
    {
        string root = Path.Combine(Path.GetTempPath(), "orders-demo");
        string inbox = Path.Combine(root, "inbox");
        string done = Path.Combine(root, "processed");
        string failed = Path.Combine(root, "failed");

        // Clean slate so the run is repeatable.
        if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
        Directory.CreateDirectory(inbox);
        Directory.CreateDirectory(done);
        Directory.CreateDirectory(failed);

        File.WriteAllText(Path.Combine(inbox, "order-1.csv"), "widget,2,9.99");
        File.WriteAllText(Path.Combine(inbox, "order-2.csv"), "gizmo,1,24.50");
        File.WriteAllText(Path.Combine(inbox, "order-3.csv"), "broken row");
        File.WriteAllText(Path.Combine(inbox, "notes.txt"), "not my business");

        string[] files = Directory.GetFiles(inbox, "*.csv");
        Array.Sort(files);

        int accepted = 0, rejected = 0;
        decimal revenue = 0m;

        foreach (string path in files)
        {
            string name = Path.GetFileName(path);
            string[] parts = File.ReadAllText(path).Split(',');

            if (parts.Length == 3 &&
                int.TryParse(parts[1], out int qty) &&
                decimal.TryParse(parts[2], NumberStyles.Number, CultureInfo.InvariantCulture, out decimal price))
            {
                revenue += qty * price;
                accepted++;
                File.Move(path, Path.Combine(done, name), overwrite: true);
                Console.WriteLine("accepted " + name + " (" + qty + " x " + price + ")");
            }
            else
            {
                rejected++;
                File.Move(path, Path.Combine(failed, name), overwrite: true);
                Console.WriteLine("rejected " + name);
            }
        }

        // Publish the report by writing beside it and swapping it in.
        string report = Path.Combine(root, "summary.txt");
        string temp = report + ".tmp";

        File.WriteAllLines(temp, new[]
        {
            "accepted: " + accepted,
            "rejected: " + rejected,
            "revenue:  " + revenue
        });
        File.Move(temp, report, overwrite: true);

        Console.WriteLine("--- " + Path.GetFileName(report) + " ---");
        foreach (string line in File.ReadLines(report))
            Console.WriteLine(line);

        Console.WriteLine("left in inbox: " + Directory.GetFiles(inbox).Length);
    }
}

Output:

accepted order-1.csv (2 x 9.99)
accepted order-2.csv (1 x 24.50)
rejected order-3.csv
--- summary.txt ---
accepted: 2
rejected: 1
revenue:  44.48
left in inbox: 1

Four decisions in that code are worth copying. Files are moved rather than deleted, so a rejected file is still there to look at tomorrow. The filter is "*.csv", so notes.txt is untouched — the one file left in the inbox. Parsing uses InvariantCulture, so a machine configured for German does not read 9.99 as nine. And the report is written to .tmp and moved, so a reader polling that folder can never catch it half-finished.


Common Mistakes

  1. Hard-coded separators. folder + "\\" + name compiles everywhere and works in one place. Path.Combine (or Path.Join) handles the separator, doubled slashes, and rooted second arguments for you.
  2. ReadAllLines on an unbounded file. A 3 GB log becomes a 3 GB string[] plus overhead. Switch to ReadLines the moment the size is not something you control.
  3. Trusting File.Exists. It answers a question about the past. Attempt the operation and catch IOException and friends instead of guarding with a check that expires immediately.
  4. Writing directly over a live file. A reader can see a truncated file, and a crash leaves it that way permanently. Write to .tmp, then File.Move(..., overwrite: true).
  5. Forgetting to create the directory. File.WriteAllText will not create missing folders; it throws DirectoryNotFoundException. Directory.CreateDirectory is safe to call every time.
  6. Assuming enumeration order. Neither GetFiles nor EnumerateFiles sorts. Sort explicitly if order matters, and remember "file10" sorts before "file9" in text order.
  7. Blocking calls in a request handler. File.ReadAllText inside a web endpoint pins a thread for the duration of the disk read. Use the Async overloads and await them.
  8. Culture-dependent parsing. decimal.Parse("9.99") throws or misreads on a machine whose decimal separator is a comma. Machine-readable files always deserve CultureInfo.InvariantCulture.

Best Practices

  • Build every path with Path.Combine, and resolve relative paths against AppContext.BaseDirectory rather than the working directory.
  • Default to ReadLines / StreamReader for input you did not create, and ReadAllText only for files you know are small.
  • Create directories before writing, and treat "already exists" as success.
  • Publish files atomically: temp file, then move.
  • Catch the specific IOException subtypes you can act on, and let the rest reach a boundary.
  • Move failures aside instead of deleting them, so there is evidence to debug.
  • Use the Async file APIs in anything that serves requests, and ConfigureAwait(false) in library code.
  • Parse and format machine-readable data with InvariantCulture on the way in and on the way out.

Practice Exercises

  1. Count without loading. Write a method that counts the lines in a file using File.ReadLines, then a second one using File.ReadAllLines. Generate a file of 500,000 lines, run both, and compare peak memory using GC.GetTotalMemory(false) before and after each.
  2. Safe overwrite. Write void Publish(string path, string content) that writes to path + ".tmp" and then moves it into place. Prove it works by throwing an exception deliberately between the write and the move, and confirming the original file is untouched.
  3. Folder report. Given a folder, print every .txt file's name and length in bytes, sorted largest first, using Directory.EnumerateFiles and FileInfo. Then add SearchOption.AllDirectories and explain what changed about both the output and the time it took.
  4. Race the check. Write code that calls File.Exists, waits for a key press, and then calls File.ReadAllText. While it waits, delete the file by hand. Note which exception you get, then rewrite the method so it handles that case without File.Exists at all.