日期:2014-05-19  浏览次数:21303 次

关于BinaryReader.Read()方法分批次读取二进制文件的问题(二进制文件特大,一次读不完)。
我用下面的方法,想将一个786MB的电影文件读到byte[]数组中。为什么执行后,程序一直处于运行状态,一直执行不到MessageBox.Show(b.Length.ToString());这一句。总是看不到最后读到byte[]数组中的大小。

难道BinaryReader.Read()只能读小的二进制文件,大的二进制文件读不了?
是不是把大的二进制文件读到byte[]数组中还有别的更好的方法?


FileStream   fs   =   new   FileStream(txb_File.Text,   FileMode.Open,   FileAccess.Read);
BinaryReader   r   =   new   BinaryReader(fs);
byte[]   b   =   new   byte[fs.Length];

for   (int   i   =   0;   i   <   fs.Length;   i   +=   200000)
{
        r.Read(b,   0,   i);
}

MessageBox.Show(b.Length.ToString());


------解决方案--------------------
FileStream fs = new FileStream(txb_File.Text, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] b = new byte[1024];
int l = 0;
int length = 0;
while(0 < (l = r.Read(b, 0, b.Length)))
{
length += l;
}

MessageBox.Show(length.ToString());

------解决方案--------------------
楼主的机器还剩786MB的内存吗?

处理大文件一般都是分块(缓冲)来处理,比如4096字节为一组
------解决方案--------------------
你要分块处理的,内存没有这么大的

------解决方案--------------------
FileStream fs = new FileStream(txb_File.Text, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] b = new byte[1024];
MemoryStream ms = new MemoryStream();
int count =0
while(count <fs.Length)
{
int read= r.Read(b, 0, b.Length);
count+=read;
ms.Write(b,0,read);
}
r.Close();
fs.Close();
MessageBox.Show(ms.Length);
//ms.ToArray()就是读取的byte[]
------解决方案--------------------
FileStream fs = new FileStream(txb_File.Text, FileMode.Open, FileAccess.Read);
System.IO.FileInfo info = new System.IO.FileInfo(txb_File.Text);
BinaryReader r = new BinaryReader(fs);
byte[] b = new byte[info.Length];
r.Read(b, 0, b.Length);
MessageBox.Show(b.Length.ToString());