Console.OpenStandardError Method in C#

This method is used to acquire a standard error stream. This method can be used to reacquire the standard error stream after it has been changed by the SetError method.


public static System.IO.Stream OpenStandardError ();

Returns: This method returns the standard error stream.

Example: The below code first checks for the string to be GeeksForGeeks and if not so then the program calls the SetError method to redirect error information to a file, calls the OpenStandardError method in the process of reacquiring the standard error stream, and indicates that error information was written to a file. The StreamWriter.AutoFlush property is set to true before reacquiring the error stream. This ensures that output will be sent to the console immediately rather than buffered.





// C# program to illustrate the 
// OpenStandardError() Method
using System;
using System.IO;
namespace GeeksforGeeks {
class GFG {
    // Main Method
    static void Main(string[] args)
        Console.WriteLine("Please Write GeeksForGeeks");
        string a;
        a = Console.ReadLine();
        // checks for a string to be GeeksforGeeks
        if (!a.Equals("GeeksForGeeks")) { 
            // Write error information to a file.
            Console.SetError(new StreamWriter(@".\Errorfile.txt"));
            Console.Error.WriteLine("The String is not GeeksForGeeks");
            // Reacquire the standard error stream.
            var standardError = new StreamWriter(Console.OpenStandardError());
            standardError.AutoFlush = true;
            Console.Error.WriteLine("\nError information written"+
                                             " to Errorfile.txt");


Executing on Cmd:

Output File:


My Personal Notes arrow_drop_up

Im a final year MCA student at Panjab University, Chandigarh, one of the most prestigious university of India I am skilled in various aspects related to Web Development and AI I have worked as a freelancer at upwork and thus have knowledge on various aspects related to NLP, image processing and web

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to 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 :

Be the First to upvote.

Please write to us at to report any issue with the above content.