[英]why is TextWriter logging to file incomplete?
我試圖在這里遵循此解決方案將我的控制台輸出也鏡像到日志文件,但是,我注意到文件的輸出被切斷,因此完整的控制台輸出未完全輸出到文件中。 這是為什么? TextWriter 是否僅限於一定數量的行?
private TextWriter txtMirror = new StreamWriter("mirror.txt");
// Write text
private void Log(string strText)
{
Console.WriteLine(strText);
txtMirror.WriteLine(strText);
}
ps 我使用這個解決方案的原因是因為我在 main() 中調用的函數中也有Console.Writeline
。 所以如果我改用這個解決方案,我將不得不在我有Console.WriteLine()
任何地方打開一個 using 語句......這似乎是多余的
您可以使用AutoFlush
屬性System_IO_StreamWriter_Flush
除非您明確調用 Flush 或 Close,否則刷新流不會刷新其底層編碼器。 將 AutoFlush 設置為 true 意味着每次寫操作后都會將數據從緩沖區刷新到流中,但不會刷新編碼器狀態。
順便說一下,如果你多次實例化你的記錄器類,你將會有很多StreamWriter
對象。 確保按照文檔處理它們
此類型實現 IDisposable 接口。 使用完類型后,應直接或間接處理它。 要直接處理類型,請在 try/catch 塊中調用其 Dispose 方法。 要間接處理它,請使用語言構造,例如 using(在 C# 中)或 Using(在 Visual Basic 中)。 有關詳細信息,請參閱 IDisposable 接口主題中的“使用實現 IDisposable 的對象”部分。
處理對象,確保調用flush
並將任何緩沖信息寫入底層對象。
例子:
// Write text
private void Log(string strText)
{
Console.WriteLine(strText);
using (StreamWriter txtMirror = new StreamWriter("mirror.txt")) {
txtMirror.WriteLine(strText);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.