C# Input & Output

Input and output (I/O) moves text and data between your program and the world: the console, files, and streams. The key namespaces are System and System.IO.

Console I/O

Output

Console.WriteLine appends a newline; Console.Write does not. String interpolation embeds values.

Console.WriteLine("Hello");
Console.Write("Sum: ");
Console.WriteLine(3 + 4);
Console.WriteLine($"Total = {3 + 4}"); // Total = 7

Input

Console.ReadLine reads a line as a string. Convert it to a number when needed.

Console.Write("Name: ");
string name = Console.ReadLine() ?? "";
Console.WriteLine($"Hi, {name}!");

Console.Write("Age: ");
int age = int.Parse(Console.ReadLine() ?? "0");
Console.WriteLine(age + 1); // next birthday

File I/O

Read File

The File class covers common text operations. Add using System.IO; to use it.

using System.IO;

string text = File.ReadAllText("notes.txt");
string[] lines = File.ReadAllLines("notes.txt");
Console.WriteLine(lines.Length);

Write File

Writing is symmetrical to reading: a single call creates the file and stores the text. Use AppendAllText to keep existing content.

using System.IO;

File.WriteAllText("out.txt", "hello");
File.AppendAllText("out.txt", "\nworld");

Streams

StreamReader

Read text line by line without loading the whole file into memory.

using System.IO;

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

StreamWriter

For incremental writes, a writer appends line by line and flushes on dispose — ideal for logs.

using System.IO;

using (var writer = new StreamWriter("log.txt", append: true))
{
    writer.WriteLine("entry");
}