2014-06-24 35 views
-1

我寫的文字使用下面的代碼使用StreamWriter文件:創建文本文件,如果動態文本文件大小超過最大容量

path == @"Desktop\"; 
filepath1 = path + "1.txt"; 
StreamWriter _sw = new StreamWriter(filepath1, true); 
_sw.WriteLine("some Text"); 
_sw.Close(); 

如果文本文件的大小超過500KB我要創建的文本文件動態。我tryng下面的代碼:

var size = (path.Length)/1024; 

if(size>=500) 
{ 
    int i = (size/500)+1; 
    var filepath2 = path + i + ".txt"; 

    if (File.Exists(filepath2)) 
    { 
     StreamWriter _sw = new StreamWriter(filepath2, true); 
     _sw.WriteLine("Some message"); 
     _sw.Close(); 
    } 
} 
else 
{ 
    FileStream fs = File.Create(filepath2); 
    StreamWriter _sw = new StreamWriter(filepath2, true); 
    _sw.WriteLine(ex); 
    _sw.Close(); 
} 

我的問題是,如果文件2.txt也超過500KB我想創建3.txt,4.txt .....等等.. 我想動態創建所有這些 - 如何解決這個問題?

回答

0

從哪裏開始..

你正在寫它作爲一個大的長程序腳本。您需要將其分解爲可使用functions重新使用的塊。事實上,它會很快失去控制。

path == @「Desktop \」;無效。 1太多=

使用Path.Combine()來結合您的文件夾和文件名。

我敢肯定,這只是測試/粗糙/劃痕代碼,但萬一不是,也檢查出嘗試/除了包裝您的文件處理。您還應該使用()來查找以處置您的流/作者。

我最後的評論是,我看到很多這種代碼很多,它通常可以替換像Nlog這樣的一個很少的摩擦。

我會評論,但此登錄沒有代表。

0

您首先需要對文件的數據長度進行SIZE比較,而不是文件路徑。

這裏是你想要達到的功能,請爲你的路徑做適當的修改。

 //Public variable to manage file names 
    int FileCounter = 1; 

    string FileName; 

    // Call this function to Add text to file 
    private void WriteToFile(string writeText) 
    { 

     FileName = "MyFile_"+FileCounter +".txt"; 
     if (File.Exists(FileName)) 
     { 
      string str = File.ReadAllText(FileName); 

      if ((str.Length + writeText.Length)/1024 > 500) // check for limit 
      { 
       // Create new File 
       FileCounter++; 
       FileName = "MyFile_" + FileCounter + ".txt"; 
       StreamWriter _sw = new StreamWriter(FileName, true); 
       _sw.WriteLine(writeText); 
       _sw.Close(); 

      } 
      else // use exixting file 
      { 
       StreamWriter _sw = new StreamWriter(FileName, true); 
       _sw.WriteLine(writeText); 
       _sw.Close(); 
      } 
     } 

    }