Skip to content

File I/O

File I/O operations allow you to read from and write to files on the file system. C# provides various classes and methods for efficient file handling.

Reading Files

File reading operations enable you to access and process file contents. C# offers multiple approaches for reading files, from simple one-line operations to more controlled streaming.

csharp
// Read all text
string content = File.ReadAllText("file.txt");

// Read lines
string[] lines = File.ReadAllLines("file.txt");

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

Writing Files

File writing operations allow you to create and modify files. C# provides methods for both simple text writing and more complex streaming scenarios.

csharp
// Write text
File.WriteAllText("file.txt", "Hello World");

// Write lines
File.WriteAllLines("file.txt", new[] { "Line 1", "Line 2" });

// Stream writing
using (StreamWriter writer = new StreamWriter("file.txt"))
{
    writer.WriteLine("Hello World");
}