本文介绍了byte [] var = new byte []抛出OutOfMemory异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经通过调用File.ReadAllBytes来读取文件,但是当我读取大文件时我得到了一个OutOfMemory异常。



所以我尝试了FileStream并成功阅读700MB文件到字节数组。



I used to read file by calling File.ReadAllBytes, but I got an OutOfMemory exception when I read large file.

So I tried FileStream and succeed in reading 700MB file into byte array.

byte[] FileByte = null;
byte[] ResByte = null;

private void ReadFile(string FilePath)
        {
            using (FileStream fs = new FileStream(this.txtFilePath.Text, FileMode.Open, FileAccess.Read))
            {
                int length = (int)fs.Length;
                this.FileByte = new byte[length];
                int count;                         
                int sum = 0;                          

                while ((count = fs.Read(this.FileByte, sum, length - sum)) > 0)
                    sum += count;
            }



但是当我尝试下面的代码时,我得到了另一个OutOfMemory异常。


But when I tried the code below, I got another OutOfMemory exception.

this.ResByte = new byte[this.FileByte.Length];





FileByte的长度约为700.000 .000,我确信.NET数组最多可以加载2GB的字节。而且,第一个字节数组成功加载。那么为什么第二个字节数组会抛出OutOfMemory异常呢?



解释会有所帮助。 :)



The length of FileByte is about 700.000.000, and I'm sure .NET array can load up to 2GB of bytes. Moreover, the first byte array successfully loaded. So how come the second byte array throw OutOfMemory exception?

An explanation will be helpful. :)

推荐答案

FileInfo fi = new FileInfo(strFile);
FileByte = new byte[fi.Length];

即。没有涉及流。

您可能值得检查您正在构建的目标:X86将具有比64位应用程序更小的对象大小限制。



我建议你需要看看这个块,而不是把它看作一个大块的块。

I.e. without the stream involved.
It may be worth your checking what target you are building for: X86 will have a smaller "object size" limit than 64 bit applications.

I would suggest that you need to look at doing this in chunks, rather than reading it as a single massive lump anyway.


这篇关于byte [] var = new byte []抛出OutOfMemory异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 17:39