System.IO Namespace

The System.IO namespace provides types that allow reading and writing to files, data streams, and memory. It is the foundation for all input/output operations in .NET.

Key Types

Reading a Text File

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string path = @"C:\Temp\example.txt";

        // Read all lines into a string array
        string[] lines = File.ReadAllLines(path);

        foreach (var line in lines)
        {
            Console.WriteLine(line);
        }
    }
}

Writing to a File (Async)

using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

class AsyncWrite
{
    static async Task Main()
    {
        string path = @"C:\Temp\async.txt";
        string content = "Hello, async world!";

        byte[] encoded = Encoding.UTF8.GetBytes(content);
        await File.WriteAllBytesAsync(path, encoded);
        Console.WriteLine("File written asynchronously.");
    }
}

Common Scenarios