写入大文本文件时抛出 OutOfMemory 异常

OutOfMemory exception thrown while writing large text file

我想生成一个字符串,然后将其写入 .txt 文件。问题是当我尝试这样做时出现 OutOfMemory 异常。

文件很大(大约 10000 行)。

我使用 String.Format 并循环创建字符串。如何将其写入 .txt 文件?

        string Text= @"...";
        const string channelScalar = @"...";
        Text= string.Format(...);
        foreach (Channel channel in ...)
        {
            switch (channel.Type)
            {
                case "...":
                    Text= string.Format(Text,
                        ChannelFrames(channel, string.Format(...);
                    break;
            }
        }
        File.WriteAllText(textBox9.Text,Text);

使用StreamWriter直接将生成的每一行写入文本文件。这避免了首先将整个长文件存储在内存中。

using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\Somewhere\whatever.txt")) 
    {
        //Generate all the single lines and write them directly into the file
        for (int i = 0; i<=10000;i++)
        {
            sw.WriteLine("This is such a nice line of text. *snort*");
        }
    }