![](/img/trans.png)
[英]How do you make Unit continuously look for a closer target and then re-assign to the primary target? Unity
[英]How do I re-assign the standard error stream such that exceptions thrown by library code also get written to file instead of the console?
在以下測試程序中,錯誤輸出正確寫入Error.txt。
using System;
using System.IO;
public class Test{
public static void Main(string[] args){
Console.SetOut(new StreamWriter("Output.txt", true));
Console.SetError(new StreamWriter("Error.txt", true));
int[] test = new int[1];
Console.Error.WriteLine(test[0]);
}
}
但是,如果我們更改線路
Console.Error.WriteLine(test[0]);
至
Console.Error.WriteLine(test[7]);
這將導致異常,此異常的錯誤消息將打印到控制台而不是文件。 我如何以編程方式進行設置,以便系統拋出的異常的錯誤消息也被重定向到文件?
由於運行此程序的上下文,簡單的控制台重定向(2>或>)不是一個選項。
我不認為Console.SetError方法實際上改變了應用程序的“DOS”錯誤輸出,就在Console.Error輸出的地方。 你應該嘗試PInvoking SetStdHandle。 例如,請參閱此處: 在C#Windows服務上重定向stdout + stderr
我相信,錯誤輸出不會像您嘗試使用它一樣工作。 它只是輸出有關某些錯誤的信息的一種方法。 看看這個http://msdn.microsoft.com/en-us/library/system.console.seterror.aspx
如果你想寫一些關於錯誤的東西,你需要做下一個:
Console.Error.WriteLine("Error Log for Application {0}", appName);
因此,如果要向stderr寫入有關異常的信息,則需要捕獲異常並將其消息定向到stderr。
...
catch(Exception e) { Console.Error.WriteLine(e.Message); }
你在找這樣的東西嗎?
FileStream errorFileStream = new FileStream("Error.txt", FileMode.OpenOrCreate);
StreamWriter errorStreamWriter = new StreamWriter(errorFileStream);
Console.SetError(errorStreamWriter);
string[] test = new string[2];
test[0] = "Hello";
test[1] = "World";
try
{
Console.WriteLine(test[2]);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
Console.Error.Close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.