当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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#。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。