【问题标题】:Text file too big to be read [duplicate]文本文件太大而无法读取[重复]
【发布时间】:2019-04-02 18:21:23
【问题描述】:

我不阅读大数据文本文件。我的文件大小约为 2GB。但是,我读取的最大文件大小为 200MB。这如何在 C# 中执行此操作。帮帮我。

private void button12_Click(object sender, EventArgs e)
{
        String file = textBox1.Text;

        if (string.IsNullOrEmpty(file))
        {
            MessageBox.Show("Файлыг заана уу!!");
        }

        else
        {  
            System.IO.FileInfo fi = new System.IO.FileInfo(file);
            System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open);
            int bufferSize = 500000000;  // file size

            using (System.IO.BufferedStream bs = new System.IO.BufferedStream(fs, bufferSize))
            {
                byte [] buffer = new byte [bufferSize];

                int readLength;
                do
                {
                    readLength = bs.Read(buffer, 0, bufferSize);
                    richTextBox1.Text += System.Text.Encoding.ASCII.GetString(buffer);
                    Application.DoEvents();

                } while (readLength == bufferSize);

                bs.Close();
            }
            fs.Close();
        }
        String names = richTextBox1.Text;

}

【问题讨论】:

  • 当您尝试读取数据时会发生什么?你有例外吗?
  • 读取600MB文件时,发生System.OutOfMemoryException错误。我知道这是一个内存问题。你对此有什么想法吗?

标签: c#


【解决方案1】:

下面这行代码你在浪费内存:

richTextBox1.Text += "some_string";

字符串是不可变的,因此每次执行此操作时,都会分配现有文本字符串大小的新内存,加上连接的字符串,并丢弃旧字符串。垃圾收集器将回收此内存,但它不一定会以足够快的速度回收以避免耗尽进程的可用内存。

至少,尝试使用StringBuilder 构建此字符串,并在循环之后分配给文本框一次。

但是,您可能仍然会遇到内存耗尽的情况,因为在窗口中显示文本的上下文中,2GB 的字符串仍然加载

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-29
    • 2015-02-01
    • 2014-06-18
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    相关资源
    最近更新 更多