File Class — Simple Read/Write
using System.IO;
// Read
string content = File.ReadAllText("data.txt");
string[] lines = File.ReadAllLines("data.txt");
byte[] bytes = File.ReadAllBytes("image.png");
// Write
File.WriteAllText("out.txt", "Hello");
File.WriteAllLines("out.txt", new[] { "line1", "line2" });
File.AppendAllText("log.txt", "new entry\n");
// Async
string content2 = await File.ReadAllTextAsync("data.txt");
await File.WriteAllTextAsync("out.txt", "Hello");
// Check
bool exists = File.Exists("data.txt");
File.Delete("temp.txt");
File.Copy("a.txt", "b.txt", overwrite: true);
File.Move("a.txt", "renamed.txt");
Directory
Directory.CreateDirectory("logs");
bool exists = Directory.Exists("logs");
Directory.Delete("logs", recursive: true);
string[] files = Directory.GetFiles("docs", "*.txt");
string[] dirs = Directory.GetDirectories("docs");
// Recursive
var allFiles = Directory.EnumerateFiles("root", "*.cs",
SearchOption.AllDirectories);
string current = Directory.GetCurrentDirectory();
Path Helper
string fullPath = Path.Combine("docs", "2024", "file.txt");
// "docs/2024/file.txt"
string ext = Path.GetExtension("photo.jpg"); // ".jpg"
string name = Path.GetFileNameWithoutExtension("photo.jpg"); // "photo"
string dir = Path.GetDirectoryName(fullPath);
string temp = Path.GetTempFileName();
StreamReader / StreamWriter
// Large file — line by line
using (var reader = new StreamReader("big.txt")) {
string line;
while ((line = reader.ReadLine()) != null) {
Console.WriteLine(line);
}
}
// Modern (using declaration)
using var writer = new StreamWriter("out.txt");
writer.WriteLine("Hello");
writer.WriteLine("World");
FileStream — Binary
using var fs = new FileStream("data.bin", FileMode.Create);
byte[] data = { 1, 2, 3, 4 };
await fs.WriteAsync(data, 0, data.Length);
// Read
using var fs2 = new FileStream("data.bin", FileMode.Open);
byte[] buffer = new byte[1024];
int read = await fs2.ReadAsync(buffer, 0, buffer.Length);
JSON Serialization
using System.Text.Json;
var person = new { Name = "Rahim", Age = 25 };
// Serialize
string json = JsonSerializer.Serialize(person);
await File.WriteAllTextAsync("p.json", json);
// Deserialize
string read = await File.ReadAllTextAsync("p.json");
var p = JsonSerializer.Deserialize<Person>(read);
// Pretty print
string prettyJson = JsonSerializer.Serialize(person,
new JsonSerializerOptions { WriteIndented = true });