檢查文件信息只會在第一次運行。您在示例代碼中獲得的信息僅與該時刻相關,並且不會跟蹤事件發生後對該文件所做的任何更改。
問題的實際原因是當您執行檢查時,相關文本編寫器的緩衝區尚未刷新。當您撥打電話以寫入文本時,它將被放入內存中,直到緩衝區已滿,或者您手動刷新它。每次調用後刷新文本編寫器,並檢查流的長度以獲得預期結果。
我已經包含了一個下面的例子,你想要什麼。
string file1 = "firstFile.txt";
// Placing these resources (FileStream and TextWriter) in using blocks ensures that their resources are released when you are done
// with them.
using (Stream fs = new FileStream(file1, FileMode.Append))
using (TextWriter tx1 = new StreamWriter(fs))
{
// This will only keep track of the file information when you call it.
// Any subsequent changes to the file will not update this variable.
FileInfo fi1 = new FileInfo(file1);
if (fi1.Length < 1024)
{
tx1.WriteLine("Babloooooooooooooooooo ");
// If you don't flush this line, you won't get an up to date value for 'length' below.
// Comment it out, and see for yourself.
tx1.Flush();
Console.WriteLine("The length is...", fs.Length);
}
else
{
Console.WriteLine("Limit reached");
}
}
還應該提到的是,沖洗作家和手動流將有性能損失,所以它並不總是最好的解決方案。在這種情況下,由於您正在處理大約1k的文件,因此它不會真正起作用,但對於有大量寫入操作的較大文件,我不會推薦它。
此外,您將注意到TextWriter和FileStream實例都被放入使用塊中。這是暴露IDisposable接口的任何類型的最佳做法。您始終可以手動處理事件,但using block將確保資源被正確清理,即使存在異常。
看起來您正在寫入其他文件'tx1'而不是'fi1'。還要確保在檢查長度時調用'fi1.Refresh()'(如果在應用程序生命週期中保持相同的'fi1'實例) –
是否還有更多的代碼沒有包含在這裏?您沒有在這段代碼中寫入文件。 – Carth
小心使用什麼編碼,1024個字符,並不總是1024B。 – Max