C# Input & Output
Console class lives in System, files and streams in System.IO, and JSON in System.Text.Json. This lesson goes from a formatted console report to reading a file line by line and saving objects as JSON.
The examples are complete dotnet new console programs (.NET 8 or later); System, System.IO and System.Linq are imported automatically. Number and date formats follow the current culture; the outputs shown are for an English culture.
Console Output
Console.WriteLine prints a value followed by a newline; Console.Write prints without one. Both accept any type and call its ToString(). To mix text and values, use string interpolation: an expression inside { } in a $"..." string.
Format Specifiers and Alignment
Inside the braces you can control the layout as {value,alignment:format}. A positive alignment right-aligns the value in that many characters, a negative one left-aligns it — enough to print neat columns. The format string chooses how the value is written:
| Format | Example | Result |
|---|---|---|
F2 fixed decimals | {3.14159:F2} | 3.14 |
N0 thousands separators | {1234567:N0} | 1,234,567 |
C currency | {9.5m:C} | $9.50 in en-US |
D5 zero-padded integer | {42:D5} | 00042 |
X hexadecimal | {255:X} | FF |
| custom date | {date:yyyy-MM-dd} | 2026-11-14 |
// Alignment and format specifiers turn plain values into a readable table.
string[] items = { "Coffee", "Bagel", "Orange juice" };
decimal[] prices = { 3.5m, 2.25m, 4m };
Console.WriteLine($"{"Item",-14}{"Price",8}");
for (int i = 0; i < items.Length; i++)
Console.WriteLine($"{items[i],-14}{prices[i],8:F2}");
Console.WriteLine($"{"Total",-14}{prices.Sum(),8:F2}");
Console.Write("No newline, ");
Console.WriteLine("then a newline.");
Console.WriteLine($"{1234567:N0} | {42:D5} | {255:X} | {DateTime.UnixEpoch:yyyy-MM-dd}");
Output:
Item Price
Coffee 3.50
Bagel 2.25
Orange juice 4.00
Total 9.75
No newline, then a newline.
1,234,567 | 00042 | FF | 1970-01-01
Standard Error and Exit Codes
A console program has two output channels. Console.Out (what WriteLine uses) is for the program's results; Console.Error is for warnings and error messages. Keeping them separate means a user can redirect the results to a file (dotnet run > out.txt) and still see the errors on screen. Programs also report success or failure to the shell with an exit code: return an int from the top-level code, where 0 means success.
Console Input
Console.ReadLine() waits for the user to press Enter and returns the line as a string, without the newline. It returns null when the input has ended — the user pressed Ctrl+Z (Windows) or Ctrl+D (Linux, macOS), or the piped input ran out — so its type is string?. What the user types is always text; convert it with TryParse and be ready for invalid input (see Type Casting).
Reading Until the End of Input
The loop below works the same whether a person types the numbers or another program pipes them in. It skips bad lines with a message on standard error instead of crashing.
// Sum numbers from standard input until a blank line or end of input.
int sum = 0, count = 0;
string? line;
while ((line = Console.ReadLine()) is not null)
{
if (string.IsNullOrWhiteSpace(line))
break;
if (int.TryParse(line, out int value))
{
sum += value;
count++;
}
else
{
Console.Error.WriteLine($"skipping '{line}'");
}
}
double average = count == 0 ? 0 : (double)sum / count;
Console.WriteLine($"{count} numbers, sum {sum}, average {average:F2}");
Output of printf "4\n8\nx\n15\n" | dotnet run:
skipping 'x'
3 numbers, sum 27, average 9.00
For single keys rather than whole lines, Console.ReadKey(intercept: true) returns a ConsoleKeyInfo without echoing the key, which is how menu programs and simple games read input.
Command-Line Arguments
Arguments typed after the program name arrive in the args array, available in top-level code without declaring anything. With dotnet run, put them after -- so the SDK does not interpret them. For real tools with many options, the System.CommandLine package parses flags and generates help text.
// greet: usage message on stderr and a non-zero exit code when arguments are missing.
if (args.Length == 0)
{
Console.Error.WriteLine("usage: greet <name> [--shout]");
return 1;
}
bool shout = args.Contains("--shout");
string message = $"Hello, {args[0]}!";
Console.WriteLine(shout ? message.ToUpper() : message);
return 0;
Output of dotnet run -- Ada --shout:
HELLO, ADA!
File I/O
The static File class does the common jobs in a single call: ReadAllText and WriteAllText for a whole file as one string, ReadAllLines and WriteAllLines for arrays of lines, AppendAllText to add to the end. Each call opens the file, does the work and closes it again. Directory creates and lists folders, and Path builds paths safely: always use Path.Combine rather than gluing strings with "\\" or "/", so the same code runs on Windows, Linux and macOS.
Reading and Writing Whole Files
// Write, append, read back and list files in a temporary folder.
string dir = Path.Combine(Path.GetTempPath(), "sage-io-demo");
Directory.CreateDirectory(dir); // no error if it already exists
string path = Path.Combine(dir, "notes.txt");
File.WriteAllLines(path, new[] { "first line", "second line" }); // creates or overwrites
File.AppendAllText(path, "third line" + Environment.NewLine);
string[] lines = File.ReadAllLines(path);
Console.WriteLine($"{lines.Length} lines, last: {lines[^1]}");
Console.WriteLine($"exists: {File.Exists(path)}");
foreach (string file in Directory.EnumerateFiles(dir, "*.txt"))
Console.WriteLine(Path.GetFileName(file));
Output:
3 lines, last: third line
exists: True
notes.txt
File operations fail for reasons outside your program — a missing file, a full disk, no permission, a file locked by another process — so production code wraps them in try/catch (IOException), as shown in Error Handling. Text is read and written as UTF-8 by default.
Streams
Reading a whole file into memory is fine for small files but not for a 5 GB log. A stream is a sequence of bytes you process piece by piece. StreamReader and StreamWriter wrap a stream and handle text and encodings; File.ReadLines (not ReadAllLines) returns the lines lazily, one at a time, so it can feed a LINQ query over a huge file. Always open streams in a using block so they are closed and flushed even when an error occurs.
StreamReader and StreamWriter
// Write a log with StreamWriter, scan it with StreamReader, then use the async API.
string source = Path.Combine(Path.GetTempPath(), "sage-log.txt");
using (var writer = new StreamWriter(source)) // flushed and closed by using
{
for (int i = 1; i <= 5; i++)
writer.WriteLine($"event {i}: {(i % 2 == 0 ? "ok" : "warn")}");
}
int warnings = 0;
using (var reader = new StreamReader(source))
{
string? line;
while ((line = reader.ReadLine()) is not null)
if (line.EndsWith("warn"))
warnings++;
}
Console.WriteLine($"{warnings} warnings");
Console.WriteLine(File.ReadLines(source).First()); // reads only the first line
await File.WriteAllTextAsync(source, "replaced");
Console.WriteLine(await File.ReadAllTextAsync(source));
Output:
3 warnings
event 1: warn
replaced
Asynchronous I/O
Most I/O methods have an Async version that returns a Task. Awaiting it frees the thread while the disk or network works, which keeps desktop applications responsive and lets a web server handle many requests with few threads. Top-level code can use await directly, as the last two lines above show. For a simple console tool the synchronous methods are fine; in ASP.NET Core and UI code, prefer the asynchronous ones.
Saving Objects as JSON
Serialize and Deserialize
Programs rarely store raw lines: they save settings, records and results. System.Text.Json, built into .NET, converts objects to JSON text and back. Records are a natural fit, since the serializer can fill their constructor parameters. JsonSerializerOptions controls details such as indentation and camelCase property names.
// Serialize a record to JSON and read it back.
using System.Text.Json;
var settings = new Settings("dark", 14, ["csharp", "sql"]);
string json = JsonSerializer.Serialize(settings);
Console.WriteLine(json);
Settings? loaded = JsonSerializer.Deserialize<Settings>(json);
Console.WriteLine($"{loaded?.Theme}, size {loaded?.FontSize}, {loaded?.Languages.Count} languages");
record Settings(string Theme, int FontSize, List<string> Languages);
Output:
{"Theme":"dark","FontSize":14,"Languages":["csharp","sql"]}
dark, size 14, 2 languages
Combine it with File.WriteAllText to save the settings, and File.ReadAllText plus Deserialize to load them on the next start. The demos 13_console_io.cs and 14_files.cs have more examples.
Practice
Exercises
- Extend the price table: read item names and prices from the user until a blank line, then print the table with the total.
- Write a
wc-like tool that takes a file name inargsand prints the number of lines, words and characters, usingFile.ReadLines. Return exit code 2 if the file does not exist. - Save a
List<Settings>to a JSON file withWriteIndented = true, open it in an editor, change a value, and load it back. - Copy a text file to a new file with every line numbered, using one
StreamReaderand oneStreamWriter.