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.
- ✓Solid grasp of fundamentals
- ✓Comfortable reading code examples
- ✓Basic production concepts
- 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
C# File I/O is the set of APIs in .NET for reading and writing files on disk, spanning System.IO.File, StreamReader/StreamWriter, FileStream, and the newer File static methods in System.IO. The core problem this article addresses is that forgetting to wrap file handles in using statements (or Dispose() calls) leaves file streams open, which on Windows locks the file exclusively until the garbage collector runs — or worse, until the process ends.
In production APIs, this manifests as IOException: The process cannot access the file because it is being used by another process, often at the worst possible moment under load. The using pattern ensures deterministic release of OS file handles, which is non-negotiable in server-side code where thousands of concurrent requests may touch the same filesystem.
File I/O in .NET operates in three layers: the high-level static methods (File.ReadAllText, File.WriteAllLines) that handle open/read/close atomically but block the calling thread; the stream-based readers/writers (StreamReader, StreamWriter) that give you line-by-line or buffered control; and the raw FileStream with its FileShare flags for fine-grained locking behavior. The high-level methods are convenient but dangerous in APIs because they block the thread for the entire I/O duration.
The async counterparts (ReadAllTextAsync, WriteAsync) are essential for non-blocking server scenarios — every millisecond a thread spends waiting on disk I/O is a thread that could be handling another request. In high-throughput services like ASP.NET Core endpoints reading CSV files, blocking on synchronous I/O can exhaust the thread pool and cause cascading latency spikes.
Defensive patterns are mandatory: check File. before reading, wrap in try-catch for Exists()DirectoryNotFoundException, UnauthorizedAccessException, and IOException (which covers locks), and use FileShare.Read when opening for concurrent read access. For structured files like CSV, the standard pattern is to open a FileStream with FileShare.Read, wrap it in a StreamReader, then parse lines — all inside using blocks.
For concurrent write scenarios, consider FileShare.None for exclusive access or use a SemaphoreSlim to serialize writes. The alternative to raw file I/O in production is to use a database (SQLite, SQL Server) or a message queue (Azure Queue, RabbitMQ) for shared state — file locking is a distributed systems anti-pattern at scale.
This article walks through a real-world CSV ingestion endpoint and shows exactly where missing using kills your API.
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.
using System; using System.IO; class FileLayersDemo { static void Main() { string filePath = "sample_log.txt"; // --- LAYER 3: File class (convenience, small files) --- // Writes all content in one shot. File is opened and closed automatically. File.WriteAllText(filePath, "Line one\nLine two\nLine three\n"); // Reads entire file into a single string — fine for small config files string entireContent = File.ReadAllText(filePath); Console.WriteLine("[File.ReadAllText output]"); Console.WriteLine(entireContent); // --- LAYER 2: StreamReader (line-by-line, memory-efficient) --- // 'using' ensures the stream is closed even if an exception is thrown Console.WriteLine("[StreamReader line-by-line output]"); using (StreamReader reader = new StreamReader(filePath)) { string? currentLine; int lineNumber = 1; // ReadLine returns null when there are no more lines while ((currentLine = reader.ReadLine()) != null) { Console.WriteLine($" Line {lineNumber++}: {currentLine}"); } } // stream is guaranteed closed here // --- LAYER 1: FileStream (raw bytes, binary data) --- Console.WriteLine("\n[FileStream byte count]"); using (FileStream rawStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { // Length gives total byte count — useful for binary files Console.WriteLine($" File size in bytes: {rawStream.Length}"); } } }
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.
using System; using System.IO; using System.Threading.Tasks; class AsyncFileOperations { // Simulates writing an application log entry asynchronously static async Task WriteLogEntryAsync(string logFilePath, string message) { // File.AppendAllTextAsync opens, appends, and closes — no stream management needed // The thread is released back to the pool while the OS handles the disk write string timestampedEntry = $"[{DateTime.UtcNow:yyyy-MM-dd HH:mm:ss}] {message}{Environment.NewLine}"; await File.AppendAllTextAsync(logFilePath, timestampedEntry); } // Reads a potentially large report file line by line without blocking static async Task<int> CountMatchingLinesAsync(string reportFilePath, string searchTerm) { int matchCount = 0; // StreamReader with 'await using' disposes asynchronously — important for async code await using (StreamReader reader = new StreamReader(reportFilePath)) { string? line; while ((line = await reader.ReadLineAsync()) != null) { // Case-insensitive search — realistic for log analysis if (line.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)) { matchCount++; } } } return matchCount; } static async Task Main() { string logPath = "application.log"; // Simulate writing several log entries await WriteLogEntryAsync(logPath, "Application started"); await WriteLogEntryAsync(logPath, "User login: alice@example.com"); await WriteLogEntryAsync(logPath, "ERROR: Database connection timeout"); await WriteLogEntryAsync(logPath, "User login: bob@example.com"); await WriteLogEntryAsync(logPath, "ERROR: Null reference in PaymentService"); Console.WriteLine($"Log file written to: {logPath}"); // Count how many ERROR lines are in the log int errorCount = await CountMatchingLinesAsync(logPath, "ERROR"); Console.WriteLine($"Total ERROR entries found: {errorCount}"); // Read and display the full log to confirm string fullLog = await File.ReadAllTextAsync(logPath); Console.WriteLine("\n--- Full Log Contents ---"); Console.WriteLine(fullLog); } }
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.
using System; using System.IO; using System.Threading; class DefensiveFileIO { // Uses Path.Combine — works on Windows (\) and Linux (/) without changes static string BuildReportPath(string baseDirectory, string reportName) { return Path.Combine(baseDirectory, "reports", $"{reportName}.txt"); } // Ensures the directory exists before writing — safe to call multiple times static void EnsureDirectoryExists(string filePath) { string? directory = Path.GetDirectoryName(filePath); if (!string.IsNullOrEmpty(directory)) { // CreateDirectory does nothing if directory already exists — no need to check first Directory.CreateDirectory(directory); } } // Retries on IOException (file lock) with exponential back-off static string ReadWithRetry(string filePath, int maxAttempts = 3) { for (int attempt = 1; attempt <= maxAttempts; attempt++) { try { return File.ReadAllText(filePath); } catch (FileNotFoundException) { // No point retrying — file genuinely doesn't exist throw; } catch (IOException ex) when (attempt < maxAttempts) { // File is locked by another process — wait and retry int delayMs = 100 * (int)Math.Pow(2, attempt); // 200ms, 400ms Console.WriteLine($" File locked (attempt {attempt}), retrying in {delayMs}ms: {ex.Message}"); Thread.Sleep(delayMs); } } throw new IOException($"Could not read '{filePath}' after {maxAttempts} attempts."); } static void Main() { string reportPath = BuildReportPath(AppDomain.CurrentDomain.BaseDirectory, "monthly_summary"); Console.WriteLine($"Target path: {reportPath}"); // Safe write — creates all missing directories automatically EnsureDirectoryExists(reportPath); File.WriteAllText(reportPath, "Monthly Revenue: $142,500\nNew Users: 3,421\n"); Console.WriteLine("Report written successfully."); // Safe read with retry try { string reportContent = ReadWithRetry(reportPath); Console.WriteLine("\n--- Report Contents ---"); Console.WriteLine(reportContent); } catch (FileNotFoundException) { Console.WriteLine("ERROR: Report file not found. Generate the report first."); } catch (UnauthorizedAccessException) { Console.WriteLine("ERROR: No permission to read report. Check file permissions."); } // Demonstrate safe check before delete if (File.Exists(reportPath)) { File.Delete(reportPath); Console.WriteLine("\nReport cleaned up."); } } }
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.
using System; using System.IO; using System.Text; class CsvProcessor { record ProductRecord(string Name, string Category, decimal Price, int StockLevel); // Streams through a CSV file line by line — memory stays flat regardless of file size static System.Collections.Generic.IEnumerable<ProductRecord> ReadProductCsv(string csvFilePath) { // detectEncodingFromByteOrderMarks handles UTF-8 BOM from Excel exports automatically using StreamReader reader = new StreamReader(csvFilePath, detectEncodingFromByteOrderMarks: true); // Skip the header row string? headerLine = reader.ReadLine(); if (headerLine == null) yield break; string? dataLine; int rowNumber = 1; while ((dataLine = reader.ReadLine()) != null) { rowNumber++; string[] columns = dataLine.Split(','); // Guard against malformed rows — real CSVs have bad data if (columns.Length != 4) { Console.WriteLine($" Skipping malformed row {rowNumber}: '{dataLine}'"); continue; } if (!decimal.TryParse(columns[2], out decimal price) || !int.TryParse(columns[3], out int stock)) { Console.WriteLine($" Skipping row {rowNumber} — invalid numeric data"); continue; } yield return new ProductRecord(columns[0].Trim(), columns[1].Trim(), price, stock); } } // Writes filtered results using temp-file-then-rename for atomicity static void WriteLowStockReport(string outputCsvPath, System.Collections.Generic.IEnumerable<ProductRecord> products) { string tempPath = outputCsvPath + ".tmp"; // AutoFlush = false — buffers writes for performance, flushed on Dispose using (StreamWriter writer = new StreamWriter(tempPath, append: false, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: true))) { writer.AutoFlush = false; writer.WriteLine("ProductName,Category,Price,StockLevel,StockStatus"); foreach (ProductRecord product in products) { if (product.StockLevel < 10) { string status = product.StockLevel == 0 ? "OUT_OF_STOCK" : "LOW_STOCK"; writer.WriteLine($"{product.Name},{product.Category},{product.Price:F2},{product.StockLevel},{status}"); } } } // buffer flushed and file closed here // Atomic rename — if process dies during write, original file is untouched File.Move(tempPath, outputCsvPath, overwrite: true); } static void Main() { string inputPath = "inventory.csv"; string outputPath = "low_stock_report.csv"; // Create sample inventory CSV for demonstration File.WriteAllText(inputPath, "Name,Category,Price,Stock\n" + "Wireless Keyboard,Peripherals,49.99,23\n" + "USB-C Hub,Peripherals,34.95,3\n" + "Webcam HD,Video,89.00,0\n" + "Monitor Stand,Accessories,29.50,INVALID\n" + // bad row — intentional "Laptop Stand,Accessories,44.99,7\n" + "HDMI Cable,Cables,12.99,145\n"); Console.WriteLine("Processing inventory CSV..."); var allProducts = ReadProductCsv(inputPath); WriteLowStockReport(outputPath, allProducts); Console.WriteLine("\n--- Low Stock Report ---"); Console.WriteLine(File.ReadAllText(outputPath)); } }
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.
using System; using System.IO; using System.Threading; namespace io.thecodeforge.FileIO { class ConcurrentFileAccess { private static readonly object _lock = new object(); static void WriteToSharedLog(string logFilePath, string message) { lock (_lock) { File.AppendAllText(logFilePath, $"{DateTime.UtcNow}: {message}{Environment.NewLine}"); } } static void Main() { string logPath = "shared.log"; // Simulate concurrent writes from multiple threads Thread t1 = new Thread(() => { for (int i = 0; i < 5; i++) WriteToSharedLog(logPath, $"Thread A - message {i}"); }); Thread t2 = new Thread(() => { for (int i = 0; i < 5; i++) WriteToSharedLog(logPath, $"Thread B - message {i}"); }); t1.Start(); t2.Start(); t1.Join(); t2.Join(); Console.WriteLine("Shared log content:"); Console.WriteLine(File.ReadAllText(logPath)); } } }
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.
// io.thecodeforge — csharp tutorial // NEVER do this — handle leak waiting to happen FileStream leakyStream = new FileStream("/var/log/app.log", FileMode.Open); byte[] buffer = new byte[1024]; leakyStream.Read(buffer, 0, buffer.Length); // ... forgot to call Dispose // CORRECT PATTERN using (FileStream safeStream = new FileStream("/var/log/app.log", FileMode.Open, FileAccess.Read, FileShare.Read)) { byte[] data = new byte[safeStream.Length]; safeStream.Read(data, 0, data.Length); } // handle released *immediately* after scope exit
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.
// io.thecodeforge — csharp tutorial // Bad: loads entire file string allText = File.ReadAllText("config.json"); // Good: stream lines one at a time string targetLine = null; using (var reader = new StreamReader("config.json")) { string line; while ((line = reader.ReadLine()) != null) { if (line.Contains(""connectionString"")) { targetLine = line; break; // stops reading early } } } Console.WriteLine(targetLine ?? "Not found");
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.
// io.thecodeforge — csharp tutorial static IEnumerable<string> SafeEnumerateFiles(string root, string pattern) { var files = new List<string>(); try { files.AddRange(Directory.EnumerateFiles(root, pattern, SearchOption.TopDirectoryOnly)); } catch (UnauthorizedAccessException ex) { Console.WriteLine($"Skipping {root}: {ex.Message}"); return files; // return whatever we got } foreach (var dir in Directory.EnumerateDirectories(root)) { files.AddRange(SafeEnumerateFiles(dir, pattern)); } return files; } // Usage var logs = SafeEnumerateFiles("/var/log/app", "*.log"); Console.WriteLine($"Found {logs.Count()} log files.");
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.
// io.thecodeforge — csharp tutorial using var fs = new FileStream( @"C:\Logs\app.log", FileMode.Append, FileAccess.Write, FileShare.Read ); using var writer = new StreamWriter(fs); writer.WriteLine("Request processed at " + DateTime.UtcNow); writer.Flush(); // Force write to OS buffer, not disk // When using 'using', Close() is called automatically. // For explicit control, call fs.Flush(true) to flush to disk.
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.
// io.thecodeforge — csharp tutorial byte[] rawData = { 0x48, 0x65, 0x6C, 0x6C, 0x6F }; // Wrong: wrapping binary in text classes using var badWriter = new StreamWriter(@"C:\Temp\data.bin"); badWriter.Write(rawData); // Writes "Hello" as string, not bytes // Right: direct FileStream for binary using var goodFile = new FileStream( @"C:\Temp\data.bin", FileMode.Create ); goodFile.Write(rawData, 0, rawData.Length); Console.WriteLine("Binary written without encoding overhead.");
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.
// io.thecodeforge — csharp tutorial using System; using System.IO; using System.Security.Principal; public static class FileAccessGuard { public static string ReadWithIdentityLog(string path) { try { return File.ReadAllText(path); } catch (UnauthorizedAccessException ex) { string identity = WindowsIdentity.GetCurrent().Name; throw new IOException( $"Failed under identity: {identity}. Path: {path}", ex); } } }
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.
// io.thecodeforge — csharp tutorial using System.IO.IsolatedStorage; using System.IO; public class CacheWriter { public static void SaveSecret(string data) { using var store = IsolatedStorageFile.GetStore( IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null); using var stream = new IsolatedStorageFileStream( "settings.dat", FileMode.Create, store); using var writer = new StreamWriter(stream); writer.Write(data); } }
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.cat file.tmp (check if temp file exists and has complete data)Head -c 100 /path/to/outputfile (check last few bytes are complete)wc -l /path/to/file (count lines to estimate file size)ls -lh /path/to/file (check file size)StreamReader.ReadLine() in a while loop. Use async variants if concurrent.| Scenario | Best API Choice | Why |
|---|---|---|
| Reading a small config file (<1 MB) | File.ReadAllText / ReadAllTextAsync | One-liner, auto-closes, sufficient for small payloads |
| Reading a large log or CSV file | StreamReader.ReadLine / ReadLineAsync | Constant memory usage regardless of file size |
| Writing binary data (images, PDFs) | FileStream with BinaryWriter | Byte-level control, no charset encoding overhead |
| Appending to an existing log file | File.AppendAllText / AppendAllTextAsync | Concise, safe, handles open/close automatically |
| High-performance bulk writing | StreamWriter with AutoFlush = false | Buffers writes, orders of magnitude faster than line-by-line flush |
| Reading all lines into a collection | File.ReadAllLines | Returns string[] directly, clean for small files with line-level iteration |
| ASP.NET Core controller file reads | Any *Async variant + await | Releases thread pool threads during disk wait, scales under load |
| Writing a file that must not corrupt | Write to .tmp, then File.Move | OS rename is atomic — original untouched if process dies mid-write |
| Concurrent writes from multiple threads | StreamWriter + lock or File.AppendAllText | Prevents data corruption; lock ensures serial access within a process |
| File | Command / Code | Purpose |
|---|---|---|
| FileLayersDemo.cs | using System; | The Three Layers of File I/O in C# |
| AsyncFileOperations.cs | using System; | Async File I/O |
| DefensiveFileIO.cs | using System; | Defensive File I/O |
| CsvProcessor.cs | using System; | Working with CSV and Structured Text Files |
| ConcurrentFileAccess.cs | using System; | File Locking and Concurrent Access |
| FileStreamLeak.cs | FileStream leakyStream = new FileStream("/var/log/app.log", FileMode.Open); | The FileStream Class |
| ReadFileProduction.cs | string allText = File.ReadAllText("config.json"); | Reading a Text File |
| TraverseSafely.cs | static IEnumerable | Directory Traversal |
| FileHandleExample.cs | using var fs = new FileStream( | Opening and Closing Files |
| ClassSelection.cs | byte[] rawData = { 0x48, 0x65, 0x6C, 0x6C, 0x6F }; | C# I/O Classes |
| SecureFileAccess.cs | using System; | I/O and Security |
| IsolatedCache.cs | using System.IO.IsolatedStorage; | Isolated Storage |
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?
If your ASP.NET Core endpoint reads a file synchronously and your app suddenly struggles under load with high thread-pool exhaustion, what's happening and how would you fix it?
await File.ReadAllTextAsync() or await reader.ReadLineAsync(). This releases the thread back to the pool during the disk wait, recovering scalability. Also ensure the entire call stack is async, or you'll get sync-over-async deadlocks.How would you safely write a file that's read by an external system, ensuring the external system never sees a partially-written or corrupted file — even if your process is killed mid-write?
File.Move(tempPath, finalPath, overwrite: true). The OS rename operation is atomic on most file systems – if the process dies during the write to the .tmp file, the original output file remains untouched. This guarantees that the external system either sees the completely old file or the completely new file, never a partial state. Pair this with a final flush and close before the rename.Frequently Asked Questions
File.ReadAllText reads the entire file into a single string in one operation — it's concise and great for small files. StreamReader reads the file incrementally, line by line or in chunks, which keeps memory usage constant regardless of file size. For any file whose size is user-controlled or unbounded, StreamReader is the safer and more scalable choice.
Use await File.ReadAllTextAsync(filePath) for small files, or 'await using (StreamReader reader = new StreamReader(filePath))' with 'await reader.ReadLineAsync()' for large ones. Both release the calling thread back to the thread pool during the disk read. This is critical in ASP.NET Core where thread-pool starvation from synchronous file reads is a real scalability problem.
The most common cause is hardcoded backslash path separators. Windows accepts both '\' and '/' in paths, but Linux treats '\' as a literal character in filenames. Replace all string-concatenated paths with Path.Combine(), which automatically uses the correct separator for the current OS. Also check that your filenames are lowercase — Linux filesystems are case-sensitive, unlike Windows.
Use the lock statement to ensure only one thread writes to a file at a time. For cross-process scenarios, use a named Mutex. Alternatively, use File.AppendAllText which opens, appends, and closes atomically, reducing the window for contention. For high-concurrency logging, consider using a dedicated logging library like Serilog that handles file locking internally.
You write the output to a temporary file (e.g., 'data.csv.tmp') and then atomically rename it to the final filename using File.Move. This ensures that if the process crashes mid-write, the target file remains untouched (either the old version or not present). It's a simple, zero-overhead way to guarantee atomic writes for files consumed by other systems.
20+ years shipping production .NET services in enterprise systems. Lessons pulled from things that broke in production.
That's C# Basics. Mark it forged?
10 min read · try the examples if you haven't