Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบว่าการป้อนข้อมูล เอาต์พุต และข้อผิดพลาดถูกเปลี่ยนเส้นทางใน Console หรือไม่ใน C#

ภาพรวม

คลาส Console มีคุณสมบัติสำหรับตรวจสอบว่าสตรีมมาตรฐานถูก redirect หรือไม่:

  • IsInputRedirected – stdin
  • IsOutputRedirected – stdout
  • IsErrorRedirected – stderr

ตัวอย่าง 1: ตรวจสอบ Input

using System;

public class Demo {
    public static void Main(string[] args) {
        Console.WriteLine("Input Redirected? = " + Console.IsInputRedirected);
    }
}

ผลลัพธ์ตัวอย่าง 1

Input Redirected? = False

ตัวอย่าง 2: ตรวจสอบ Output (หมายเหตุ: โค้ดต้นฉบับใช้ IsInputRedirected ซ้ำ)

using System;

public class Demo {
    public static void Main(string[] args) {
        Console.WriteLine("Output Redirected? = " + Console.IsOutputRedirected);
    }
}

ผลลัพธ์ตัวอย่าง 2

Output Redirected? = False

ตัวอย่าง 3: ตรวจสอบ Error

using System;

public class Demo {
    public static void Main(string[] args) {
        Console.WriteLine("Error Redirected on Console? = " + Console.IsErrorRedirected);
    }
}

ผลลัพธ์ตัวอย่าง 3

Error Redirected on Console? = True

สรุป

  • คุณสมบัติทั้งสามเป็น bool อ่านอย่างเดียว
  • มีประโยชน์เมื่อโปรแกรมรันในสคริปต์หรือ pipeline ที่ redirect สตรีม
  • ตัวอย่างที่ 2 ในต้นฉบับมีข้อผิดพลาด (ใช้ IsInputRedirected แทน IsOutputRedirected) – 已修正ในตัวอย่างนี้