In C#, Console.SetError replaces the TextWriter for standard error. Messages written with Console.Error.WriteLine go to that writer.
Keeping errors separate from normal output helps logs and pipelines. Pair with SetOut when you need both streams redirected differently.
This is a static member of System.Console. You call it with the type name, such as Console.SetError(...). Console is the everyday API for reading from standard input and writing to standard output in C# console apps.
Syntax
Pass a TextWriter, then write through Console.Error.
OpenStandardError returns the raw stderr Stream if you need a lower-level handle.
Library declarations
C#
public static void SetError(TextWriter newError);
Parameters
Parameter
Description
newError
Required. The TextWriter that becomes standard error.
Return Value
Return Value
Description
void
Error output is redirected.
C# Examples
Example 1 — Capture Console.Error Into a String
Redirect stderr, write an error, then show the capture on stdout.
C#
using System;
using System.IO;
class Program {
static void Main() {
var err = new StringWriter();
var original = Console.Error;
Console.SetError(err);
Console.Error.WriteLine("file missing");
Console.SetError(original);
Console.WriteLine("captured: " + err.ToString().Trim());
}
}
Output
captured: file missing
How It Works
Separate stream. Error text does not go through Out while redirected.
StringWriter. Holds the diagnostic in memory.
Restore Error. Put the original writer back.
Report on Out. Print a summary with WriteLine.
Example 2 — Write Normal and Error Messages
Show that Out and Error are independent.
C#
using System;
class Program {
static void Main() {
Console.WriteLine("status: ok");
Console.Error.WriteLine("diag: check logs");
}
}
Output
status: ok
diag: check logs
How It Works
WriteLine → Out. Normal status message.
Error.WriteLine. Diagnostic on stderr.
Both visible. Many terminals show them together.
Pipelines differ. Shells can split the streams.
Example 3 — Send Errors to TextWriter.Null
Silence diagnostics temporarily.
C#
using System;
using System.IO;
class Program {
static void Main() {
var original = Console.Error;
Console.SetError(TextWriter.Null);
Console.Error.WriteLine("hidden");
Console.SetError(original);
Console.WriteLine("done");
}
}
Output
done
How It Works
Null error writer. Discards Error writes.
Hidden diag. Does not appear in output.
Restore. Later errors can show again.
done on Out. Normal output still works.
Frequently Asked Questions
For diagnostics and failures you want on stderr, separate from normal program output.
No. WriteLine uses Out. Use Console.Error.WriteLine for the error writer.
Yes. SetError to a StringWriter and read ToString().