【问题标题】:StreamWriter crashes with large text files in C#StreamWriter 在 C# 中因大文本文件而崩溃
【发布时间】:2011-12-27 02:18:45
【问题描述】:

我正在使用 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();
            }

【问题讨论】:

  • 你有没有产生你所说的问题的代码示例?
  • “超过 50 个字” - 这不是“大”
  • 它给出了一个 IO 异常,我会在几秒钟内放我的代码。
  • 您能否通读一下:stackoverflow.com/editing-help 然后尝试修复您的代码格式和缩进。谢谢。
  • 修复这个怎么样。您确实意识到您在此处发布的内容不仅是为了您的利益,也是为了可能遇到相同问题的其他用户?那么,为什么不现在就进行一些练习并修复它呢?

标签: c# file text streamwriter


【解决方案1】:

试试这个。您只需在使用前立即创建 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++;
    } 

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

    • @HenkHolterman 我刚刚提出了一个建议,它对用户有用。有问题吗?
    • 它解决了崩溃问题。现在我接受了超过 50 个单词的文本,并且它可以正常工作而不会崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多