當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# Console.SetOut()用法及代碼示例


C#中的Console.SetOut(TextWriter)方法用於重定向標準輸出流。借助此方法,用戶可以將StreamWriter指定為輸出對象。 Console.SetOut方法將接收類型為TextWriter的對象。可以將StreamWriter傳遞給Console.SetOut,並將其隱式轉換為TextWriter類型。它隻是將標準輸出流屬性設置為其獲取的指定TextWriter對象。

用法:

public static System.IO.TextWriter Out { get; }
                or
public static void SetOut (System.IO.TextWriter newOut);
                or
public static void SetOut(TextWriter newOut)

返回值:它將streamWriter返回到指定的TextWriter對象。


異常:

  • 當newOut為null時,拋出ArgumentNullException,它不接受它作為有效參數。
  • 發生I /O錯誤時,將引發IOException。

示例1:

// C# code to demonstrate the use  
// of Console.SetOut method 
using System; 
using System.IO; 
  
class GFG { 
  
    // Main Method 
    static void Main() 
    { 
  
        // Creating a text file named "out" in D Drive 
        using(StreamWriter writer = new StreamWriter("D:\\out.txt")) 
        { 
            Console.SetOut(writer); 
            Result(); 
        } 
    } 
  
    // Method Result 
    static void Result() 
    { 
  
        // Writing to the file 
        Console.WriteLine("GeeksforGeeks"); 
        Console.WriteLine("A Computer Science portal for Geeks!"); 
    } 
}

編譯和執行:

輸出:

示例2:

// C# code to demonstrate the use  
// of Console.SetOut method 
using System; 
using System.IO; 
  
class GFG { 
  
    // Main Method 
    static void Main() 
    { 
  
        // will display on console 
        Console.WriteLine("\nGeeksForGeeks"); 
  
        // Creating a text file named "Geeks"  
        // at the location of your program 
        FileStream geeks1 = new FileStream("Geeks.txt", FileMode.Create); 
  
        // Standard Output stream is  
        // being saved to a Textwriter 
        TextWriter geeksave = Console.Out; 
  
        StreamWriter portal1 = new StreamWriter(geeks1); 
        Console.SetOut(portal1); 
  
        Console.WriteLine("\nThe Computer Science portal for Geeks"); 
  
        Console.WriteLine("\nWelcome to GeeksforGeeks"); 
        Console.SetOut(geeksave); 
  
        // will display on console 
        Console.WriteLine("This is Console.SetOut Method in C#"); 
        Console.WriteLine("Get programming practices at your own pace !"); 
        portal1.Close(); 
    } 
}

編譯和執行:

參考:



相關用法


注:本文由純淨天空篩選整理自MerlynShelley大神的英文原創作品 Console.SetOut() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。