Labs ICT
Pro Login

File I/O

Reading and writing files is something almost every app does eventually. C# makes it easy with the System.IO namespace and helper methods on the File class.

Reading All Text

File.ReadAllText reads an entire file into a string in one shot. Perfect for small to medium files.


string content = File.ReadAllText("data.txt");
Console.WriteLine(content);
    
Try it Yourself →

Writing All Text

File.WriteAllText creates a file (or overwrites it) and writes your string into it.


string text = "Hello, file!";
File.WriteAllText("output.txt", text);
Console.WriteLine("Written!");
    

There's also File.AppendAllText if you want to add to an existing file instead of replacing it.

StreamReader and StreamWriter

For larger files or line-by-line processing, use StreamReader and StreamWriter. They read and write one line at a time, which uses way less memory.


using (StreamWriter writer = new StreamWriter("notes.txt"))
{
    writer.WriteLine("First line");
    writer.WriteLine("Second line");
}

using (StreamReader reader = new StreamReader("notes.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}
    

The using statement ensures the file gets closed even if something goes wrong. Always wrap file streams in using.

Checking If a File Exists

Before opening a file, check it's there. File.Exists returns true if the file exists, false otherwise.


string path = "data.txt";

if (File.Exists(path))
{
    string content = File.ReadAllText(path);
    Console.WriteLine(content);
}
else
{
    Console.WriteLine("File not found");
}
    

This prevents a FileNotFoundException and lets you handle missing files gracefully.

Paths and Using

You'll need using System.IO; at the top of your file to access these classes. File paths can be relative (like "data.txt") or absolute (like "C:\folder\data.txt").