C# File I/O — Missing `using` Locked Production API
Production API failed with 'file in use' IOException from a missing using block.
20+ years shipping production .NET services in enterprise systems. Lessons pulled from things that broke in production.
- C# File I/O offers three layers: File static class, StreamReader/StreamWriter, and FileStream
- File.ReadAllText loads everything into memory – use only for files under ~10MB
- StreamReader.ReadLine() keeps memory flat regardless of file size, essential for unbounded files
- Async variants (ReadAllTextAsync, ReadLineAsync) release threads during disk wait, preventing thread-pool starvation under load
- Not disposing streams leaves files locked – leads to IOException in production bug reports
- Biggest mistake: using File.ReadAllLines on user-uploaded CSVs – server crashes with OutOfMemoryException
Think of your hard drive as a giant filing cabinet. Your C# program is the office worker who needs to pull out a document, read it, maybe scribble some notes on it, and then put it back. File I/O is simply the set of instructions that tells that office worker HOW to open the drawer, handle the document carefully, and close the drawer when done — without losing any pages or jamming the cabinet.
File I/O in C# looks simple—until it silently locks your production API at 2 AM. A missing using statement, a blocked thread on a disk read, or a naive one-liner for a text file can tank performance or crash your service entirely. This article walks through the real pitfalls: the three abstraction layers you can’t ignore, the hidden cost of synchronous I/O, defensive patterns for missing files and concurrent access, and the exact spots where memory leaks breed in FileStream. No fluff—just the sharp edges every senior dev hits when working with files in .NET.
Why Missing `using` in C# File I/O Locks Production APIs
C# file I/O is the mechanism for reading from and writing to the filesystem via the System.IO namespace. The core mechanic is that file handles are unmanaged resources: the OS kernel tracks them, and the .NET runtime cannot automatically reclaim them. When you open a file with FileStream, StreamReader, or StreamWriter, you acquire an exclusive or shared lock on that file handle. If you fail to release it—by not calling Dispose() or not wrapping the call in a using block—the handle remains open until the garbage collector runs a finalizer, which is non-deterministic and can take seconds to minutes.
In practice, this means that a production API endpoint that reads or writes a file without a using block will eventually fail under load. The first few requests succeed, but as handles accumulate, subsequent attempts to open the same file throw IOException: The process cannot access the file because it is being used by another process. The lock is per-handle, not per-thread, so even single-threaded code can deadlock itself if it opens a file, doesn't close it, and then tries to reopen it. The using statement compiles to a try/finally that calls Dispose(), which closes the handle immediately—this is O(1) and deterministic.
You must use using for every file I/O operation in production systems, especially in web APIs where concurrent requests are the norm. The pattern is trivial: using var fs = new FileStream(path, FileMode.Open);. Skipping it is not a style choice; it's a reliability defect. In high-throughput scenarios, even a single leaked handle can cascade into a full outage when all available file handles (default 8192 on Windows, often lower in containers) are exhausted.
using caused a production outage after 30 minutes of peak traffic: the process hit the 8192-handle limit, all subsequent file operations threw IOException, and the API returned 500 errors for every request until the process was restarted.new FileStream, File.OpenRead, or File.WriteAllText must be wrapped in using or called via a helper that guarantees disposal—no exceptions.using or try/finally; the using statement is syntactic sugar for correct disposal.The Three Layers of File I/O in C# — and Why They Exist
C# gives you three distinct levels of abstraction for file work, each built on top of the one below it. Understanding this layering is what stops you from grabbing the wrong tool.
At the lowest level you have FileStream — raw bytes, maximum control, maximum verbosity. Above that sit StreamReader and StreamWriter, which wrap a FileStream and add character encoding and line-by-line text handling. At the top sits the static File class, which wraps everything into single-line convenience methods like File.ReadAllText and File.WriteAllLines.
The File class is perfect for small files where simplicity matters — it opens the file, does the work, and closes it all in one call. But it reads the entire file into memory at once, which is a problem when that file is 2 GB of server logs. That's when you drop down to StreamReader and read line by line, keeping your memory footprint flat regardless of file size.
FileStream is the layer you reach for when you need binary data — images, PDFs, serialized objects — or when you need fine-grained control over file sharing modes and access permissions.
Most real-world apps live in the middle layer. Know that the File convenience methods are literally just wrappers around streams — there's no magic, just convenience.
File.ReadAllText / File.WriteAllText for files under ~10 MB where simplicity wins. Switch to StreamReader / StreamWriter the moment file size is unbounded or user-controlled — an uploaded CSV could be 500 MB.StreamReader.ReadLine(), maintaining constant memory usage with no code complexity cost.Async File I/O — Why Blocking a Thread on Disk Reads is a Hidden Performance Killer
Here's the thing most tutorials skip: disk I/O is slow. Not 'slightly slower than memory' slow — we're talking microseconds vs milliseconds. On a web server handling 500 concurrent requests, if each request reads a file synchronously, each one blocks a thread for that entire disk-wait time. Thread pool threads are a finite resource. Block enough of them and your server stops accepting new requests even though the CPU is sitting at 2% utilisation.
Async file I/O solves this by releasing the thread back to the pool while it waits for the disk. The thread goes off and serves other requests. When the disk responds, .NET picks up any available thread to continue the work.
File.ReadAllTextAsync and StreamReader.ReadLineAsync are the async counterparts you need. They return Task<string> and Task<string?> respectively, meaning you await them without blocking.
One critical nuance: StreamReader does NOT automatically buffer async reads efficiently when you call ReadLineAsync repeatedly in a tight loop on .NET 5 and earlier. On .NET 6+ this was fixed. If you're on an older runtime, prefer ReadToEndAsync or use FileStream with useAsync: true directly.
Async file operations belong in any application that handles concurrent workloads — ASP.NET Core controllers, background workers, and queue processors absolutely should not use synchronous file APIs.
async void instead of async Task for file methods means any exception thrown during the async operation is unobservable — it won't be caught by your try/catch and will silently crash the process. Always return Task or Task<T> from async file methods.Defensive File I/O — Handling Missing Files, Locked Resources and Directory Errors
Production file code fails in ways your dev machine never shows you. The config file doesn't exist on first run. The log directory hasn't been created yet. Another process has locked the file. The disk is full. A relative path resolves to a completely different location when deployed.
Defensive file I/O means anticipating these realities before they become 3am incident alerts.
The key exceptions to know are FileNotFoundException (file doesn't exist), DirectoryNotFoundException (parent directory missing), IOException (file locked, disk full, network drive disconnected), and UnauthorizedAccessException (permissions). Catching the base IOException catches most of them, but be specific when the recovery action differs.
For directories: always call Directory.CreateDirectory before writing — it's idempotent and won't throw if the directory already exists. This one pattern eliminates an entire class of deployment bugs.
For locked files: the right pattern is a retry loop with exponential back-off, not a bare try/catch that swallows the error. A locked file often means another process is actively writing to it and will be done in milliseconds.
For paths: use Path.Combine instead of string concatenation — it handles directory separators correctly across Windows, Linux, and macOS. Hardcoded backslashes are a cross-platform bug waiting to happen.
Directory.CreateDirectory is idempotent — calling it when the directory already exists doesn't throw an exception. This makes it safe as a defensive first step before any file write, no Directory.Exists check required.Working with CSV and Structured Text Files — A Real-World End-to-End Pattern
Almost every business application eventually processes CSV files — imports, exports, data migrations. This is where all the concepts above converge into a pattern you'll actually use.
The key insight for large CSV processing is streaming: read one line at a time, process it, move on. Never ReadAllLines a CSV that users upload — you're handing users a memory exhaustion attack vector. A 100 MB CSV with ReadAllLines allocates all 100 MB at once. With StreamReader.ReadLine you hold one line in memory at a time.
Encoding also matters in the real world. CSVs from Windows systems often arrive in Windows-1252 encoding. CSVs from Excel often have a UTF-8 BOM. StreamReader can auto-detect the BOM if you pass detectEncodingFromByteOrderMarks: true, which saves you from mysterious £ characters replacing £ signs.
For writing, StreamWriter with AutoFlush = false is dramatically faster than flushing after every line — let the OS buffer accumulate and flush at natural boundaries. If the process dies mid-write you'll lose the buffer, so pair this with a write-to-temp-file-then-rename pattern for atomicity.
The temp-file-then-rename pattern is the professional's choice for any file that must not be corrupted if the process dies mid-write: write to report.tmp, then File.Move("report.tmp", "report.csv", overwrite: true). The OS rename is atomic on most filesystems.
File.Move with overwrite: true (available from .NET 3.0) makes it a one-liner. Use it for any file that another system depends on.File Locking and Concurrent Access — Protecting Shared Resources
When multiple processes or threads try to access the same file, you need to think about concurrency. The default FileShare mode is FileShare.Read, which allows other processes to read the file while your stream is open for writing. But if two threads write to the same file simultaneously, you'll get data corruption or exceptions.
For a single process, use the lock statement to ensure only one thread writes at a time. For cross-process coordination, you'll need a named Mutex or a dedicated file-locking mechanism.
The FileStream constructor accepts a FileShare parameter that controls what other processes can do while your handle is open. Common combinations: - FileMode.Open, FileAccess.Read, FileShare.Read – multiple readers, no writers. - FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read – exclusive write, others can read. - FileMode.Open, FileAccess.ReadWrite, FileShare.None – exclusive access.
For high-concurrency logging, use a dedicated logging library (Serilog, NLog) that handles file locking internally. Writing your own lock-based file access is a recipe for deadlocks and performance issues.
If you must write to a shared file, use File.AppendAllText or File.AppendAllTextAsync – they open, append, and close in one atomic operation, minimising the window for contention.
lock won't work because it's per-process. Use a named Mutex or rely on a file-locking mechanism like FileStream with FileShare.None. But ideally, use a logging library or a message queue instead of sharing files.lock statement around file writes. Avoid holding the lock for long operations.File.AppendAllText – it opens, appends, and closes atomically, reducing contention window.The FileStream Class — Where Most Memory Leaks Start
FileStream is the lowest-level managed wrapper around the Win32 CreateFile/ReadFile/WriteFile API. It gives you raw byte access to files. That sounds powerful. It is. It’s also the fastest way to leak handles and corrupt data if you don’t understand what you’re touching.
Every FileStream instance holds an operating system handle. If you forget to Dispose it, that handle stays open until the garbage collector runs finalizers. On a production server under load, GC might not run for minutes. During that window, any other process — including your own app trying to write the same file — gets SHARING_VIOLATION.
The constructor signature gives you control: FileMode, FileAccess, FileShare. The trap is FileShare.None. That locks the file exclusively. If you use FileShare.Read, concurrent reads work, but writes still block. Know your access pattern before you open the stream.
Always wrap FileStream in a using block. Always. There is no excuse. If you need to hold the stream open longer, implement IDisposable and marshal the lifetime explicitly. Your production API will thank you.
Reading a Text File — Why Your Colleague's One-Liner Is Slow
You’ve seen it: File.ReadAllText(path). It’s convenient. It also loads the entire file into memory as one string. For config files under 100KB, fine. For production logs that hit 500MB, it’s a memory allocation that triggers GC pressure and a potential OutOfMemoryException.
ReadAllText and ReadAllLines are convenience wrappers over FileStream with StreamReader. They read everything, close the stream, and return. If you only need the first ten lines, you just wasted CPU and memory reading the rest.
The production pattern: use StreamReader and read line-by-line. That gives you incremental processing. Memory stays flat. If the file is small, fine — but make the habit explicit. When your log file grows to 2GB because someone forgot rotation, your one-liner won’t crash the process.
Same applies for writing. File.WriteAllText will buffer and flush in one shot. For writing 10MB of data, that’s a blocking call on the main thread. Use StreamWriter with auto-flush disabled and flush manually after logical batches.
Think about the lifecycle of your data before you type that one-liner.
File.ReadLines() (not ReadAllLines) for lazy enumeration. It returns an IEnumerable<string> backed by a StreamReader. Perfect for large files where you only need to iterate once.Directory Traversal — The Hidden Permission Nightmare
Listing files in a folder sounds trivial. Directory.GetFiles(path) does it in one line. Until your app runs as a service account that doesn’t have read permission on a subdirectory. Then you get UnauthorizedAccessException. The entire enumeration fails. You catch nothing.
Directory.GetFiles and Directory.EnumerateFiles stop at the first access denied error. EnumerateFiles is lazy, but still throws on iteration of that specific entry. If you’re crawling a deep directory tree, a single locked folder kills the whole operation.
The fix: manual recursion with try/catch per subdirectory. That means more code, but also more reliability. If you don’t need the tree, don’t recurse — flatten with SearchOption.TopDirectoryOnly.
Another trap: Path.Combine with user input. Always use Path.GetFullPath to prevent directory traversal attacks where someone passes "../../etc/shadow" as a path segment. Even if your app doesn’t run as root, they could overwrite files in parent directories.
Permission checks are I/O operations too. They cost. Don’t call Directory.Exists on every loop — cache results.
Opening and Closing Files — Where Most Devs Forget the OS Matters
Opening a file in C# isn't just about calling File.. Every open call is a handshake with the Windows or Linux kernel — requesting a handle, setting access modes, and claiming a spot in the system's file table. Close it wrong and you leak handles, lock other processes out, or corrupt data.OpenRead()
The most common production mistake? Depending on the garbage collector to close your file. That's like expecting a janitor to lock your server room door. GC timing is unpredictable, and on a loaded system, your file stays locked long after the method exits. That's why using statements exist — they force deterministic release of the OS handle.
But using alone isn't enough when you're dealing with shared network drives or high-frequency logging. In those cases, explicit Flush() and Close() calls give you surgical control over when data hits the disk. Remember: the OS buffers writes. Your Write() call might return successfully while the data is still in RAM, waiting for a flush that never happens if your app crashes.
File.Close() inside a finally block without null-checking the stream. If the constructor throws, you crash with NullReferenceException instead of handling the original I/O error.using for safety, add Flush(true) when you need to guarantee the byte is on the platter before the next line runs.C# I/O Classes — The Hierarchy That Makes or Breaks Your Architecture
Most devs treat File, FileInfo, FileStream, and StreamReader like interchangeable hammers. They're not. Each class exists for a specific performance tradeoff and lifetime pattern. Mixing them up is how you end up with StreamReader holding a 500 MB file in memory because you used ReadToEnd() instead of a buffered loop.
File is a static utility class — fine for one-off reads on small files. FileInfo gives you instance-based metadata caching, critical when you check Exists or Length repeatedly in the same scope. Underneath both sits FileStream, the actual OS handle wrapper. Wrap it in StreamReader/StreamWriter for text, BinaryReader/BinaryWriter for raw bytes, GZipStream for compression.
The senior move? Know when to skip the wrappers. If you're writing raw binary data like protobuf or image files, go straight to FileStream. The text adapters add encoding overhead and a character buffer you don't need. Same logic applies to network streams — wrapper classes add latency that kills throughput on high-frequency trading or real-time dashboards.
File.ReadAllText() is for configs under 1 MB. For anything larger — logs, CSVs, images — use FileStream with an appropriate buffer size (typically 4096 or 8192 bytes).File for tiny jobs, FileInfo for repeated access, FileStream for everything else. Text wrappers are conveniences, not optimizations.I/O and Security — Why Permissions Fail Silently in Production
Security checks in C# file I/O are not upfront. The ACL is evaluated at the OS kernel level during the actual read or write syscall, not when you construct a FileStream or call File.Exists(). This means you can successfully open a handle only to have the next operation throw an UnauthorizedAccessException. The root cause: .NET caches nothing about identity or rights; each I/O call re-evaluates against the current Windows identity or Linux user context. Impersonation, process elevation, or even a network share's credential mismatch can flip success to failure between statements. Always wrap individual I/O operations, not whole blocks, in structured exception handling. Use WindowsIdentity.RunImpersonated or the equivalent Linux set*id calls only at the boundary. Never assume that a preceding permission check (e.g. File.GetAccessControl) implies success — that creates a TOCTOU race. The practical rule: catch UnauthorizedAccessException separately from IOException and log the WindowsIdentity name at the point of failure. This single habit saves hours of debugging permission-related file locks.
File.Exists() returns false for paths you have no permission to read, misleading you into thinking the file is missing instead of access-denied.WindowsIdentity.GetCurrent().Name on UnauthorizedAccessException.Isolated Storage — The Sandbox You Didn't Know You Needed
Isolated storage provides a per-user, per-assembly data silo that bypasses ACL nightmares in shared hosting or partial-trust environments. Instead of computing paths like C:\Users\{user}\AppData, you call IsolatedStorageFile.GetStore() with assembly evidence. The store isolates by user, domain, and assembly strong name — collisions are impossible without impersonation. Two use cases kill it: (1) temporary cache files that must survive app restarts but never leak to other users on a terminal server; (2) configuration data for ClickOnce or XBAP apps where unrestricted FileIOPermission is denied. The API is counterintuitive — you create streams via store.CreateFile(), not File.Create(). The biggest mistake: forgetting that isolated storage is subject to quota limits. The default quota is 9 MB for .NET Framework, and exceeding it throws InsufficientMemoryException. Always call store.IncreaseQuotaTo() with a required size before writing large files. In modern .NET, you should also verify that the assembly is not running under an impersonated token, or the user isolation breaks. Prefer this over manual path construction when safety from cross-user leaks is non-negotiable.
IncreaseQuotaTo() first.The Locked Log File: How a Missing `using` Statement Brought Down a Production API
using block. The garbage collector eventually finalizes the object, but not before the file handle remains open for an indeterminate time, causing contention with health checks.using statements (or await using), ensuring immediate release of the file handle.- Always wrap IDisposable file objects in using blocks.
- Never rely on garbage collection to close file handles — it's non-deterministic.
- Use File.AppendAllText for simple appends to avoid manual stream management.
detectEncodingFromByteOrderMarks: true to handle UTF-8 BOM. Avoid platform default encoding.lsof /path/to/file (Linux) or handle.exe -a -FileAccess="filename" (Windows)Get-Process | Where-Object { $_.Modules.FileName -match 'filename' } (PowerShell)using blocks immediately. If using async, use await using.Key takeaways
Common mistakes to avoid
3 patternsNot disposing StreamReader/StreamWriter
Dispose() even if an exception is thrown, which flushes the buffer and releases the OS file handle.Using File.ReadAllLines on user-uploaded or unbounded files
StreamReader.ReadLine() in a while loop. You hold one line in memory at a time. If you need IEnumerable<string> semantics, wrap it in a generator method with yield return.Building file paths with string concatenation
Interview Questions on This Topic
What's the difference between File.ReadAllText and StreamReader, and when would you choose one over the other in a production application?
Frequently Asked Questions
20+ years shipping production .NET services in enterprise systems. Lessons pulled from things that broke in production.
That's C# Basics. Mark it forged?
12 min read · try the examples if you haven't