难以将大文件读入字节数组 [英] Difficulty reading large file into byte array

查看:76
本文介绍了难以将大文件读入字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常大的BMP文件,我必须一次读取所有文件,因为在将其写入临时文件时需要反转字节.该BMP为1.28GB,出现内存不足"错误.我无法完全读取它(使用ReadAllBytes)或使用缓冲区到二进制数组中,因为我无法初始化该大小的数组.我也无法使用缓冲区将其读取到列表中(然后可以通过Reverse()来读取它),因为在此过程中途内存不足.

I have a very large BMP file that I have to read in all at once because I need to reverse the bytes when writing it to a temp file. This BMP is 1.28GB, and I'm getting the "Out of memory" error. I can't read it completely (using ReadAllBytes) or using a buffer into a binary array because I can't initialize an array of that size. I also can't read it into a List (which I could then Reverse()) using a buffer because halfway through it runs out of memory.

基本上,问题是,我如何向后读取一个很大的文件(即从LastByte开始到FirstByte结束),然后将其写入磁盘?

So basically the question is, how do I read a very large file backwards (ie, starting at LastByte and ending at FirstByte) and then write that to disk?

奖金:将反向文件写入磁盘时,请勿写入最后54个字节.

Bonus: when writing the reversed file to disk, do not write the last 54 bytes.

推荐答案

使用 StreamReader 对象,您可以

With a StreamReader object, you can Seek (place the "cursor") to any particular byte, so you can use that to go over the entire file's contents in reverse.

示例:

const int bufferSize = 1024;
string fileName = 'yourfile.txt';

StreamReader myStream = new StreamReader(fileName);
myStream.BaseStream.Seek(bufferSize, SeekOrigin.End);

char[] bytes = new char[bufferSize];
while(myStream.BaseStream.Position > 0)
{
    bytes.Initialize();
    myStream.BaseStream.Seek(bufferSize, SeekOrigin.Current);
    int bytesRead = myStream.Read(bytes, 0, bufferSize);
}

这篇关于难以将大文件读入字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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