SyntaxStudy
Sign Up
C# File and Directory Operations
C# Beginner 1 min read

File and Directory Operations

The `System.IO` namespace provides `File`, `Directory`, `Path`, and stream types for working with the file system. The static `File` class covers common single-step operations: reading all text, writing all text, copying, moving, deleting, and checking existence. `Directory` provides equivalent operations for folders. `Path` is a utility class for manipulating file-path strings in a platform-safe way. Methods like `Path.Combine`, `Path.GetExtension`, and `Path.GetFileNameWithoutExtension` remove the need to manually concatenate strings with backslashes, and they work correctly on both Windows and Unix. .NET 8 adds `File.OpenHandle` for low-level file I/O and improves `RandomAccess` APIs for concurrent reading and writing at arbitrary offsets. For most applications the high-level `File.ReadAllTextAsync` and `File.WriteAllTextAsync` async overloads are the right choice.
Example
// File, Directory, and Path operations

using System.IO;

string baseDir = Path.Combine(Path.GetTempPath(), "csharp_demo");
Directory.CreateDirectory(baseDir);

// Write a text file
string filePath = Path.Combine(baseDir, "hello.txt");
await File.WriteAllTextAsync(filePath, "Hello, file I/O!\nSecond line.");

// Read back
string content = await File.ReadAllTextAsync(filePath);
Console.WriteLine(content);

// Append
await File.AppendAllTextAsync(filePath, "\nThird line appended.");

// Read all lines into an array
string[] lines = await File.ReadAllLinesAsync(filePath);
Console.WriteLine($"Line count: {lines.Length}");

// File metadata
var info = new FileInfo(filePath);
Console.WriteLine($"Size: {info.Length} bytes, Modified: {info.LastWriteTime}");

// Copy and move
string copyPath = Path.Combine(baseDir, "hello_copy.txt");
File.Copy(filePath, copyPath, overwrite: true);

string movedPath = Path.Combine(baseDir, "subdir", "moved.txt");
Directory.CreateDirectory(Path.GetDirectoryName(movedPath)!);
File.Move(copyPath, movedPath, overwrite: true);

// Enumerate files with a glob pattern
foreach (string f in Directory.EnumerateFiles(baseDir, "*.txt", SearchOption.AllDirectories))
    Console.WriteLine(Path.GetRelativePath(baseDir, f));

// Cleanup
Directory.Delete(baseDir, recursive: true);
Console.WriteLine("Cleanup complete.");