Labs ICT
Pro Login

File I/O

Most applications need to read from or write to files. Whether it is saving user data, reading a configuration file, or generating a report — file I/O is something you will do often in .NET.

Reading Files

The simplest way to read a file is with File.ReadAllText():

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

// Read all lines into an array
string[] lines = File.ReadAllLines("data.txt");
foreach (string line in lines)
{
    Console.WriteLine(line);
}

For large files, reading everything at once can use too much memory. In that case, use StreamReader to read line by line:

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

The using statement ensures the file is properly closed when you are done, even if an error occurs. Always use it when working with files.

Writing Files

// Write text to a file (creates or overwrites)
File.WriteAllText("output.txt", "Hello, World!\nThis is a new line.");

// Append to an existing file
File.AppendAllText("output.txt", "\nAnother line added.");

// Write multiple lines
string[] lines = { "First line", "Second line", "Third line" };
File.WriteAllLines("list.txt", lines);

Be careful — WriteAllText and WriteAllLines overwrite the file completely. If you want to keep the existing content, use AppendAllText or AppendAllLines.

Checking If a File Exists

if (File.Exists("config.txt"))
{
    string config = File.ReadAllText("config.txt");
    Console.WriteLine(config);
}
else
{
    Console.WriteLine("Config file not found. Creating default...");
    File.WriteAllText("config.txt", "theme=dark\nlanguage=en");
}

Always check if a file exists before trying to read it. This prevents your program from crashing with a FileNotFoundException.

Working with Directories

// Create a directory
Directory.CreateDirectory("reports");

// Get all files in a directory
string[] files = Directory.GetFiles("reports");
foreach (string file in files)
{
    Console.WriteLine(Path.GetFileName(file));
}

// Get all subdirectories
string[] dirs = Directory.GetDirectories(".");

// Delete a file
File.Delete("output.txt");