Console.SetError() Method in C#

The Console.SetError(TextWriter) Method sets the Error property of the specified StreamWriter i.e., it redirects the standard error stream to a file. As the console is set with this StreamWriter object, the WriteLine() method can be called to write the error into the file.

Syntax: public static void SetError (System.IO.StreamWriter newError);

Parameter:
newError: It is a stream which is the new standard error output.



Exception: This method will throw the ArgumentNullException if the parameter passed is null. Also, since it uses the StreamWriter object, it’s exceptions should also be taken care of.

Example: In this example, the SetError() method is used to set the StreamWriter object to the console, and the error messages will be written into a log file from the Console.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate 
// the SetError() method
using System;
using System.IO;
  
class GFG {
  
    // Main Method
    static void Main()
    {
        // Define file to receive error stream.
        string fn = "F:\\gfg_error.log";
  
        // Define the new error StreamWriter object
        StreamWriter errStream = new StreamWriter(fn);
  
        // Redirect standard error stream to file.
        Console.SetError(errStream);
  
        // Write the error message into the Log file
        Console.Error.WriteLine("Error line is written into the log file.");
        Console.Error.WriteLine("Keep coding geeks!");
  
        // Close redirected error stream.
        Console.Error.Close();
    }
}

chevron_right


Output: The gfg_error.log file will now have the error messages in it.

Reference:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.