Console I/O
suggest changeIn .NET, the System.Console class provides static methods and properties to interact with standard input (stdin), standard output (stdout), and standard error (stderr) streams.
1. Outputting Text
Console.Write and Console.WriteLine
Console.Write: Outputs text without appending a trailing newline.Console.WriteLine: Outputs text followed by the current platform's line terminator (\r\non Windows,\non Linux/macOS).
using System;
Console.Write("Processing... ");
Console.WriteLine("Done!");
// String interpolation with formatting
string user = "Alice";
decimal balance = 1250.75m;
DateTime now = DateTime.Now;
Console.WriteLine($"User: {user}, Balance: {balance:C}, Logged in: {now:yyyy-MM-dd HH:mm:ss}");
Writing to Standard Error
Separate diagnostic messages or errors from normal output so they can be redirected independently in shell scripts:
Console.Error.WriteLine("Error: Invalid configuration file provided.");
Terminal Colors and Formatting
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[SUCCESS] Database migration completed.");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[WARNING] Disk space is below 15%.");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Failed to connect to server.");
// Always reset to prevent color bleeding
Console.ResetColor();
2. Reading User Input
Reading Strings with Console.ReadLine()
Console.ReadLine() reads the next line of characters from the standard input stream. It returns null if the end of stream (EOF / Ctrl+Z / Ctrl+D) is reached.
using System;
Console.Write("Enter your name: ");
string? name = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(name))
{
Console.WriteLine($"Hello, {name.Trim()}!");
}
else
{
Console.WriteLine("No name was entered.");
}
Parsing Typed Input Safely
Always use TryParse to prevent unhandled format exceptions:
Console.Write("Enter your age: ");
string? input = Console.ReadLine();
if (int.TryParse(input, out int age) && age >= 0)
{
Console.WriteLine($"In 10 years, you will be {age + 10}.");
}
else
{
Console.Error.WriteLine("Invalid integer entered.");
}
Reading Keystrokes with Console.ReadKey()
Console.ReadKey() reads the next key pressed by the user immediately, without waiting for the Enter key.
Console.WriteLine("Press 'Y' to confirm or 'N' to cancel: ");
ConsoleKeyInfo keyInfo = Console.ReadKey(intercept: true); // intercept = true hides the typed char
if (keyInfo.Key == ConsoleKey.Y)
{
Console.WriteLine("Action confirmed.");
}
else
{
Console.WriteLine("Action cancelled.");
}
Securely Reading Passwords (Masking Input)
using System;
using System.Text;
string ReadPassword(string prompt)
{
Console.Write(prompt);
var password = new StringBuilder();
while (true)
{
ConsoleKeyInfo key = Console.ReadKey(intercept: true);
if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
if (key.Key == ConsoleKey.Backspace)
{
if (password.Length > 0)
{
password.Remove(password.Length - 1, 1);
Console.Write("\b \b"); // Erase last asterisk on screen
}
}
else if (!char.IsControl(key.KeyChar))
{
password.Append(key.KeyChar);
Console.Write("*");
}
}
return password.ToString();
}
string pass = ReadPassword("Enter secret password: ");
3. Controlling Cursor and Screen
You can manipulate the terminal window and cursor position for text-based dashboards or interactive CLI tools:
// Clear the terminal screen
Console.Clear();
// Hide the cursor
Console.CursorVisible = false;
// Move cursor to specific column and row (0-indexed)
Console.SetCursorPosition(left: 10, top: 5);
Console.Write("Dashboard Status: OK");
// Simple progress bar
for (int i = 0; i <= 100; i += 10)
{
Console.SetCursorPosition(left: 0, top: 7);
Console.Write($"Progress: [{new string('#', i / 10)}{new string('-', 10 - i / 10)}] {i}%");
System.Threading.Thread.Sleep(50);
}
Console.WriteLine();
Console.CursorVisible = true;
4. Detecting Redirection and Stream Redirection
When running in automated scripts or CI/CD pipelines, your console application may be receiving input piped from another command or outputting into a file:
if (Console.IsInputRedirected)
{
// Reading data from a pipe or redirected file: e.g. cat input.txt | myapp
string? pipedLine;
while ((pipedLine = Console.ReadLine()) != null)
{
Console.WriteLine($"Processed: {pipedLine}");
}
}
else
{
Console.WriteLine("Running in interactive terminal mode.");
}
You can also programmatically redirect standard output to a file or stream:
using System.IO;
using (var writer = new StreamWriter("output.log"))
{
TextWriter originalOut = Console.Out;
Console.SetOut(writer);
Console.WriteLine("This line goes directly into output.log.");
// Restore standard output
Console.SetOut(originalOut);
}
5. Handling Graceful Shutdown (Ctrl+C)
Listen to Console.CancelKeyPress to intercept termination signals and clean up resources before exiting:
Console.CancelKeyPress += (sender, args) =>
{
Console.WriteLine("\nReceived termination signal. Cleaning up temporary files...");
// Set args.Cancel = true to prevent immediate process death if manual cleanup is needed
args.Cancel = false;
};
6. Summary and Best Practices
- Differentiate stdout and stderr: Use
Console.Error.WriteLinefor errors and warnings so automation pipelines can capture clean data. - Always handle nulls: Remember
Console.ReadLine()can returnnullat EOF. - Reset terminal colors: Always invoke
Console.ResetColor()in atry...finallyblock if changing terminal colors. - Check
Console.IsInputRedirected: Avoid calling interactive methods likeConsole.ReadKey()when standard input is redirected, as it will throw anInvalidOperationException.