Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy Standard Input và Output Stream qua Console trong C#

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ínhKiểuMặc địnhDùng cho
Console.InTextReaderBàn phím (stdin)Read, ReadLine, ReadToEnd
Console.OutTextWriterMàn hình (stdout)Write, WriteLine
Console.ErrorTextWriterMà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).