Mục đích
Ba thuộc tính static của Console cho biết luồng chuẩn (stdin, stdout, stderr) có đang bị **redirect** (chuyển hướng) sang file, pipe, hoặc ứng dụng khác hay không.
Thuộc tính
| Thuộc tính | Kiểu | Mô tả |
|---|---|---|
Console.IsInputRedirected | bool | True nếu stdin không phải bàn phím (ví dụ: pipe, file input). |
Console.IsOutputRedirected | bool | True nếu stdout không phải màn hình console (ví dụ: pipe, file output). |
Console.IsErrorRedirected | bool | True nếu stderr không phải màn hình console. |
Ví dụ 1: Kiểm tra Input Redirected
using System;
public class Demo
{
public static void Main(string[] args)
{
Console.WriteLine($"Input Redirected? {Console.IsInputRedirected}");
}
}
Kết quả (chạy bình thường)
Input Redirected? False
Ví dụ 2: Kiểm tra Output Redirected
using System;
public class Demo
{
public static void Main(string[] args)
{
Console.WriteLine($"Output Redirected? {Console.IsOutputRedirected}");
}
}
Kết quả (chạy bình thường)
Output Redirected? False
Ví dụ 3: Kiểm tra Error Redirected
using System;
public class Demo
{
public static void Main(string[] args)
{
Console.WriteLine($"Error Redirected? {Console.IsErrorRedirected}");
}
}
Kết quả (chạy bình thường)
Error Redirected? False
Thử nghiệm Redirect (Command Line)
# Windows cmd / PowerShell / Linux bash
dotnet run < input.txt # IsInputRedirected = True
dotnet run > output.txt # IsOutputRedirected = True
dotnet run 2> error.txt # IsErrorRedirected = True
dotnet run < in.txt > out.txt 2> err.txt # Cả 3 đều True
Ứng dụng thực tế
using System;
public class Demo
{
public static void Main()
{
// Nếu output bị redirect -> tắt màu ANSI, progress bar, prompt interative
if (Console.IsOutputRedirected)
{
Console.WriteLine("Chạy ở chế độ batch/pipe - tắt UI đẹp mắt.");
}
else
{
// Interactive mode: có thể dùng Console.CursorLeft, màu sắc,...
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Chạy tương tác - bật UI đầy đủ.");
Console.ResetColor();
}
// Log lỗi luôn ra stderr (dù redirect hay không)
Console.Error.WriteLine($"[LOG] App started at {DateTime.Now}");
}
}
Lưu ý
- Giá trị được xác định **lúc khởi động** tiến trình. Không thay đổi khi gọi
Console.SetOut/SetError/SetIntrong code. - Trên một số IDE (Visual Studio Debug Console), các giá trị có thể khác so với terminal thật.
- Dùng để quyết định: có in progress bar/color/prompt không, có flush ngay không, format log thế nào.