How to Read and Write Files in C#

How to Read and Write Files in C#

How to Read and Write Files in C#

The System.IO namespace provides everything needed to work with files and directories in C#.

Step 1 — Read All Text at Once

// Read entire file as string
string content = File.ReadAllText("data.txt");

// Read all lines into an array
string[] lines = File.ReadAllLines("data.txt");

// Async versions (preferred in web apps)
string content = await File.ReadAllTextAsync("data.txt");
string[] lines = await File.ReadAllLinesAsync("data.txt");

Step 2 — Write Text to a File

// Write (creates or overwrites)
await File.WriteAllTextAsync("output.txt", "Hello, World!");

// Append to existing file
await File.AppendAllTextAsync("log.txt", $"[{DateTime.UtcNow}] Event occurred\n");

// Write multiple lines
string[] lines = ["Line 1", "Line 2", "Line 3"];
await File.WriteAllLinesAsync("output.txt", lines);

Step 3 — Stream Large Files

// Read line by line — memory efficient for large files
await using var reader = new StreamReader("large.csv");
while (!reader.EndOfStream)
{
    string? line = await reader.ReadLineAsync();
    // process line
}

// Write with StreamWriter
await using var writer = new StreamWriter("output.csv", append: false);
await writer.WriteLineAsync("id,name,value");
await writer.WriteLineAsync("1,Alice,100");

Step 4 — Work with Paths

string dir      = Path.GetDirectoryName("logs/app.log")!; // "logs"
string name     = Path.GetFileName("logs/app.log");         // "app.log"
string noExt    = Path.GetFileNameWithoutExtension("app.log"); // "app"
string full     = Path.GetFullPath("../data.txt");          // absolute path
string combined = Path.Combine("uploads", "2025", "file.pdf");

// Check existence before acting
if (File.Exists(combined))
{
    File.Delete(combined);
}
All Comments