C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# File Operations

C# File Operations

The System.IO namespace provides everything you need to read, write, and manage files.

1 - Read and Write

// 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" });

2 - StreamReader / StreamWriter

// 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");

3 - File Info and Management

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);

4 - Working with Paths

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"

Note: Always use using statements with StreamReader, StreamWriter, and any other IDisposable file types. This guarantees the file handle is closed even if an exception occurs.

-Tip-

C# {"id":44,"topic_id":3,"name":"C# File I\/O","slug":"c-file-io","image":null,"description":"<p>Read and write files, work with directories, and handle paths in C#.<\/p>","icon":null,"class":null,"color":null,"status":0,"order":13,"created_at":"2026-05-03T02:03:02.000000Z","updated_at":"2026-05-03T02:03:02.000000Z"} - List of Contents

Related Tutorials: