Byte[stream.length] - 内存不足异常,最好的解决方法? [英] Byte[stream.length] - out of memory exception, best way to solve?

查看:18
本文介绍了Byte[stream.length] - 内存不足异常,最好的解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文件中读取字节流.但是,当我尝试读取字节时,我得到一个

i am trying to read the stream of bytes from a file. However when I try to read the bytes I get a

由于内存不足,函数求值被禁用异常

The function evaluation was disabled because of an out of memory exception

很简单.但是,解决此问题的最佳方法是什么?它是否也一次围绕 1028 的长度循环?或者有更好的方法吗?

Quite straightforward. However, what is the best way of getting around this problem? Is it too loop around the length at 1028 at a time? Or is there a better way?

我使用的 C#

BinaryReader br = new BinaryReader(stream fs);

// The length is around 600000000
long Length = fs.Length;

// Error here
bytes = new byte[Length];

for (int i = 0; i < Length; i++)
{
   bytes [i] = br.ReadByte();
}

谢谢

推荐答案

好吧.首先.想象一个大小为例如的文件2GB.您的代码将分配 2GB 的内存.只需阅读您真正需要的文件部分,而不是一次阅读整个文件.其次:不要做这样的事情:

Well. First of all. Imagine a file with the size of e.g. 2GB. Your code would allocate 2GB of memory. Just read the part of the file you really need instead of the whole file at once. Secondly: Don't do something like this:

for (int i = 0; i < Length; i++)
{
   bytes [i] = br.ReadByte();
}

效率很低.要读取流的原始字节,您应该使用以下内容:

It is quite inefficient. To read the raw bytes of a stream you should use something like this:

using(var stream = File.OpenRead(filename))
{
    int bytesToRead = 1234;
    byte[] buffer = new byte[bytesToRead];

    int read = stream.Read(buffer, 0, buffer.Length);

    //do something with the read data ... e.g.:
    for(int i = 0; i < read; i++)
    {
        //...
    }
}

这篇关于Byte[stream.length] - 内存不足异常,最好的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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