C# VS2026
Lesson 14 of 30

File Input and Output

C# in Visual Studio 2026 — a hands-on guide for developers at every level.

Reading a Text File

// Read all lines at once
string[] lines = File.ReadAllLines("data.txt");
foreach (var line in lines)
    Console.WriteLine(line);

// Read entire file as one string
string content = File.ReadAllText("data.txt");

Writing to a Text File

File.WriteAllText("output.txt", "Hello, file!
");
File.AppendAllText("output.txt", "Second line
");
File.WriteAllLines("list.txt", new[] { "a", "b", "c" });

StreamReader and StreamWriter

Use streams when processing large files line by line without loading everything into memory:

using var reader = new StreamReader("big.txt");
while (!reader.EndOfStream)
{
    string? line = await reader.ReadLineAsync();
    Console.WriteLine(line);
}

using var writer = new StreamWriter("out.txt");
await writer.WriteLineAsync("Written with StreamWriter");

Working with Paths

string folder = Path.Combine(Environment.GetFolderPath(
    Environment.SpecialFolder.Desktop), "MyData");

Directory.CreateDirectory(folder);  // create if missing

string file = Path.Combine(folder, "notes.txt");
File.WriteAllText(file, "Saved to Desktop!");

Console.WriteLine(File.Exists(file)); // True