Mục đích
Console.In (TextReader), Console.Out (TextWriter), Console.Error (TextWriter) cung cấp truy cập thấp (low-level) đến standard streams. Cho phép redirect, đọc/ghi trực tiếp.
Ví dụ 1: Standard Input Stream
using System;
public class Demo
{
public static void Main(string[] args)
{
Console.WriteLine("Standard Input Stream: " + Console.In);
// System.IO.TextReader+SyncTextReader
}
}
Ví dụ 2: Standard Output Stream
using System;
public class Demo
{
public static void Main(string[] args)
{
Console.WriteLine("Standard Output Stream: " + Console.Out);
// System.IO.TextWriter+SyncTextWriter
}
}
Ứng dụng: Redirect Input/Output
using System;
using System.IO;
public class Demo
{
public static void Main()
{
// Redirect Input từ file
using (var sr = new StreamReader("input.txt"))
{
Console.SetIn(sr);
string line = Console.ReadLine(); // Đọc từ file
Console.WriteLine($"Đọc được: {line}");
}
// Redirect Output ra file
using (var sw = new StreamWriter("output.txt"))
{
Console.SetOut(sw);
Console.WriteLine("Dòng này ghi vào file output.txt");
}
// Khôi phục mặc định
var standardOutput = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };
Console.SetOut(standardOutput);
Console.WriteLine("Đã khôi phục stdout ra màn hình.");
}
}
Đặc điểm Stream
| Thuộc tính | Kiểu | Mặc định | Dùng cho |
|---|---|---|---|
| Console.In | TextReader | Bàn phím (stdin) | Read, ReadLine, ReadToEnd |
| Console.Out | TextWriter | Màn hình (stdout) | Write, WriteLine |
| Console.Error | TextWriter | Màn hình (stderr) | Error.WriteLine, log lỗi |
Lưu ý
Console.ReadLine()=Console.In.ReadLine().Console.WriteLine()=Console.Out.WriteLine().- Redirect bằng
Console.SetIn/SetOut/SetErrorảnh hưởng **toàn bộ process**. - Trong pipe/redirect command line:
IsInputRedirected,IsOutputRedirected,IsErrorRedirected= true. - Encoding mặc định: UTF-8 (có thể đổi qua
Console.OutputEncoding).
So sánh với File I/O trực tiếp
- Console streams: tiện cho CLI tool, pipe, interop, test tự động.
- FileStream/StreamReader: kiểm soát chi tiết (buffer, encoding, seek, share mode).