Console.SetOut() Method in C#
Last Updated :
08 Nov, 2019
Console.SetOut(TextWriter) Method in C# is used to redirect the stream of standard output. With the help of this method, a user can specify a StreamWriter as the output object. The Console.SetOut method will receive an object of type TextWriter. The StreamWriter can be passed to Console.SetOut and it is implicitly cast to the TextWriter type. It simply sets the standard output stream property to the specified TextWriter object it gets.
Syntax:
public static System.IO.TextWriter Out { get; }
or
public static void SetOut (System.IO.TextWriter newOut);
or
public static void SetOut(TextWriter newOut)
Return Value: It returns the streamWriter to specified TextWriter Object.
Exceptions:
- When the newOut is null ArgumentNullException is thrown which does not accept it as a valid argument.
- When an I/O error occurred IOException is thrown.
Example 1:
using System;
using System.IO;
class GFG {
static void Main()
{
using (StreamWriter writer = new StreamWriter( "D:\\out.txt" ))
{
Console.SetOut(writer);
Result();
}
}
static void Result()
{
Console.WriteLine( "GeeksforGeeks" );
Console.WriteLine( "A Computer Science portal for Geeks!" );
}
}
|
Compiling and Executing:
Output:
Example 2:
using System;
using System.IO;
class GFG {
static void Main()
{
Console.WriteLine( "\nGeeksForGeeks" );
FileStream geeks1 = new FileStream( "Geeks.txt" , FileMode.Create);
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);
Console.WriteLine( "This is Console.SetOut Method in C#" );
Console.WriteLine( "Get programming practices at your own pace !" );
portal1.Close();
}
}
|
Compiling and Executing:
Reference:
Share your thoughts in the comments
Please Login to comment...