Roadmap › C# Language — Basics to Advanced › Module: Files and Streams
Lessons in this course (38)

31. File, Directory and Path — quick file operations

BasicMediumLesson 31 of 38

The static classes in System.IO do one-line file work:

csharp
string folder = Path.Combine(AppContext.BaseDirectory, "data");   // builds paths with the right separator (\ or /)
Directory.CreateDirectory(folder);                                  // no error if it already exists
string file = Path.Combine(folder, "notes.txt");

File.WriteAllText(file, "Line 1\n");               // create or overwrite
File.AppendAllText(file, "Line 2\n");              // add to the end
File.WriteAllLines(file, ["a", "b", "c"]);
string all = File.ReadAllText(file);
string[] lines = File.ReadAllLines(file);           // whole file in memory
foreach (var line in File.ReadLines(file))          // lazy — one line at a time, good for big files
    Console.WriteLine(line);

if (File.Exists(file)) File.Copy(file, Path.Combine(folder, "backup.txt"), overwrite: true);
File.Move(file, Path.Combine(folder, "renamed.txt"));
File.Delete(Path.Combine(folder, "backup.txt"));

foreach (var csv in Directory.EnumerateFiles(folder, "*.csv", SearchOption.AllDirectories))
    Console.WriteLine(Path.GetFileName(csv));

Console.WriteLine(Path.GetExtension("report.pdf"));            // .pdf
Console.WriteLine(Path.GetFileNameWithoutExtension("report.pdf")); // report
string temp = Path.GetTempFileName();

await File.WriteAllTextAsync(file, "async version");          // async versions for servers/UI apps

Watch out for: missing folders (DirectoryNotFoundException), files locked by another process (IOException), permissions (UnauthorizedAccessException), and building paths with string concatenation (use Path.Combine). Never build paths from user input without validating them (path traversal like ..\..\web.config).