The System.IO namespace provides everything you need to read, write, and manage files.
// Read entire file
string content = File.ReadAllText("data.txt");
// Read all lines as array
string[] lines = File.ReadAllLines("data.txt");
foreach (string line in lines)
Console.WriteLine(line);
// Write (overwrites)
File.WriteAllText("output.txt", "Hello, World!\n");
// Append
File.AppendAllText("output.txt", "Second line\n");
// Write array of lines
File.WriteAllLines("list.txt", new[] { "Item 1", "Item 2", "Item 3" });
// Read large files line by line
using var reader = new StreamReader("big-file.txt");
while (!reader.EndOfStream)
{
string? line = reader.ReadLine();
Console.WriteLine(line);
}
// Write
using var writer = new StreamWriter("log.txt", append: true);
writer.WriteLine($"[{DateTime.Now}] App started");
File.Exists("data.txt"); // true/false
File.Copy("src.txt", "dst.txt"); // copy
File.Move("old.txt", "new.txt"); // rename/move
File.Delete("temp.txt"); // delete
var info = new FileInfo("data.txt");
Console.WriteLine(info.Length); // bytes
Console.WriteLine(info.LastWriteTime);
string full = Path.Combine("C:\Users", "Alice", "docs", "report.pdf");
Path.GetFileName(full); // "report.pdf"
Path.GetExtension(full); // ".pdf"
Path.GetDirectoryName(full); // "C:\Users\Alice\docs"
Path.GetFileNameWithoutExtension(full); // "report"