StreamWriter在C#中与大文本文件崩溃

时间:2011-11-11 14:53:09

标签: c# file text streamwriter

我正在使用StreamWriter写入文件。当我使用10-50字文本的文本时,它可以正常工作。然而,当我再次调用该函数时(超过50个单词),它崩溃了。为什么会这样?有什么建议吗?

以下是代码:

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();
            }

2 个答案:

答案 0 :(得分: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++;
    } 

答案 1 :(得分:-3)

试试这个:

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