The System.IO namespace provides everything needed to work with files and directories in C#.
// 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");
// 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);
// 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");
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