写入大型文本文件时抛出OutOfMemory异常 [英] OutOfMemory exception thrown while writing large text file

查看:144
本文介绍了写入大型文本文件时抛出OutOfMemory异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

文件很大(大约10000行).

The file is large (about 10000 lines).

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

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

推荐答案

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

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

这篇关于写入大型文本文件时抛出OutOfMemory异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆