2013-11-26 108 views
0

我正在寫入文本文件。我想要文本文件在最大1024B。當此限制到達我想要顯示的消息,但這if (fi1.Length < 1024)檢查工作不將文本文件的大小與值進行比較

string file1 = "firstFile.txt"; 
TextWriter tx1 = new StreamWriter(new FileStream(file1, FileMode.Append)); 
FileInfo fi1 = new FileInfo(file1); 

if (fi1.Length < 1024) 
{  
    tx1.WriteLine("Babloooooooooooooooooo {0} ", i); 
} 
else 
{ 
    Console.WriteLine("Limit reached") 
} 
+2

看起來您正在寫入其他文件'tx1'而不是'fi1'。還要確保在檢查長度時調用'fi1.Refresh()'(如果在應用程序生命週期中保持相同的'fi1'實例) –

+1

是否還有更多的代碼沒有包含在這裏?您沒有在這段代碼中寫入文件。 – Carth

+1

小心使用什麼編碼,1024個字符,並不總是1024B。 – Max

回答

3

檢查文件信息只會在第一次運行。您在示例代碼中獲得的信息僅與該時刻相關,並且不會跟蹤事件發生後對該文件所做的任何更改。

問題的實際原因是當您執行檢查時,相關文本編寫器的緩衝區尚未刷新。當您撥打電話以寫入文本時,它將被放入內存中,直到緩衝區已滿,或者您手動刷新它。每次調用後刷新文本編寫器,並檢查流的長度以獲得預期結果。

我已經包含了一個下面的例子,你想要什麼。

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將確保資源被正確清理,即使存在異常。

+0

太棒了!像魅力一樣工作 – user2968369

+0

@ user2968369我在答案中添加了摘要。請閱讀。 –

0

文本保存到一個文件中檢查是否字符串大於1024之前,如果是隻拿一部分yourStr.Substring( 0,1024)保存此部分並顯示消息。

您應該知道文件大小取決於編碼。

 var str = "asdasdasd"; 

     using (var sw = new StreamWriter("file.txt")) 
     { 
      var temp = str; 
      if (temp.Length > 1024) 
      { 
       temp = temp.Substring(0, 1024); 
       Console.WriteLine("Limit reached"); 
      } 

      sw.Write(temp); 
     } 
+0

您正在檢查字符串寫入大小而不是文件大小 – kenny

+0

是的我知道,但您可以簡單地分配文件內容或將此變量切換到文件的內容。 – Krzysztof

+0

我認爲你錯過了這個問題的意圖,可能只是誤解了它。 – kenny

相關問題