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

M.k*_*ary 0 c# text out-of-memory file-writing

我想生成一个字符串,然后将其写入.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);
Run Code Online (Sandbox Code Playgroud)

Jen*_*ens 9

使用a 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*");
        }
    }
Run Code Online (Sandbox Code Playgroud)