2011-11-11 40 views
-2

我正在使用StreamWriter寫入文件。當我使用10-50個字的文字時,它可以正常工作。但是,當我再次調用該函數(超過50個字)時,它崩潰。這是爲什麼發生?有什麼建議麼?StreamWriter在C中與大文本文件崩潰#

這裏是代碼:

StreamWriter file = new StreamWriter("text6.txt"); 
file.Close(); 

     int count = 0; 
     string temp = ""; 
     string temp2 = ""; 

     for (Match m = Regex.Match(str, qmatch2); m.Success; m = m.NextMatch()) 
     { 
      temp = m.Value; 
      temp2 = Regex.Replace(temp, qmatch2, " . "); 
      str = Regex.Replace(str, temp, temp2); 
     } 

if (temp.Contains(".") == false) 
      { 
       file = File.AppendText("text6.txt"); 
       file.WriteLine(" " + temp); 
       count++; 
       file.Close(); 
      } 
+0

您是否有能夠產生您所說的問題的代碼示例? –

+0

您是否將StreamWriter包裝在try/catch塊中?拋出什麼異常? –

+3

「超過50個單詞」 - 這不是'大' –

回答

-3

試試這個:

StreamWriter file; 
try 
{ 
    file = new StreamWriter("text6.txt"); 
    file.Close(); 
} 
catch(Exception) 
{ 
    throw; 
} 
+0

它爲我工作,謝謝。 – LuckySlevin

+3

這確實沒有什麼...... –

+0

@HenkHolterman我剛剛提出了一個建議,它爲用戶工作。問題? – LuckySlevin

3

試試這個。您只需在使用之前立即創建StreamWriter,並將其封裝在using塊中即可確保在完成使用後立即丟棄該流。

int count = 0; 
    string temp = ""; 
    string temp2 = ""; 

    for (Match m = Regex.Match(str, qmatch2); m.Success; m = m.NextMatch()) 
    { 
     temp = m.Value; 
     temp2 = Regex.Replace(temp, qmatch2, " . "); 
     str = Regex.Replace(str, temp, temp2); 
    } 

    if (temp.Contains(".") == false) 
    { 
     using (var file = new StreamWriter("text6.txt")) 
     { 
      file.Write("text6.txt"); 
      file.WriteLine(" " + temp);      
     } 
     count++; 
    }