在C#中,我有一个在STDERR
上显示错误的函数。我想在父catch / try
STDERR
的所有内容
bool status = true;
Console.WriteLine("Action status: ");
try {
talkative_function();
} catch {
Console.WriteLine("Error");
status = false;
}
if (status) Console.WriteLine("Ok");
我目前的输出是:
Action status:...System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it 127.0.0.1:1234
at System.Net.Sockets.TcpClient.Connect(String hostname, Int32 port)
at MyProject.MyClass.MyMethod() Error
想要的输出是:
Action status: Error
如何实现这个?
答案 0 :(得分:1)
您可以使用以下
Console.SetError(TextWriter.Null);
bool status = true;
Console.Write("Action status: ");
try {
talkative_function();
} catch {
Console.WriteLine("Error");
status = false;
}
if (status) Console.WriteLine("Ok");
请注意,我还将Console.WriteLine("Action status: ");
更改为Console.Write("Action status: ");
,以便在您需要时将消息显示在一行