OutOfMemory exception thrown while writing large text file

最后都变了- 提交于 2019-12-08 10:02:36

问题


I want to generate a string and then write it in to a .txt file. The problem is I get OutOfMemory exceptions when I attempt to do so.

The file is large (about 10000 lines).

I use String.Format and loops to create the string. How can I write this to a .txt file?

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

回答1:


Use a StreamWriter to directly write each line you generate into the textfile. This avoids storing the whole long file in memory first.

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*");
        }
    }


来源:https://stackoverflow.com/questions/30536982/outofmemory-exception-thrown-while-writing-large-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!