我正在使用Filestream读大文件(> 500 MB),我得到OutOfMemoryException。OutOfMemoryException当我读取500MB FileStream
有关它的任何解决方案。
我的代码是:
using (var fs3 = new FileStream(filePath2, FileMode.Open, FileAccess.Read))
{
byte[] b2 = ReadFully(fs3, 1024);
}
public static byte[] ReadFully(Stream stream, int initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
请,这是最好的代码,我用这个:http://www.yoda.arachsys.com/csharp/readbinary.html 感谢老总 – 2010-05-11 13:04:29
+1:是的,分配你需要的缓冲区大小是好主意......实际上,我很惊讶.NET没有将整个文件读入字节数组或其他类似结构的方法。 – Powerlord 2010-05-12 14:30:54
它的确如此。 File.ReadAllBytes http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx但这不是这张海报应该做的。将500MB文件的所有字节读入内存通常是个坏主意,在这种情况下,这是一个非常糟糕的主意。这个海报显然有一个主要的但没有说明的目标,它不是“将文件的所有字节读入内存”。他*认为*他需要读取所有字节,但事实并非如此。 – Cheeso 2010-05-20 11:50:37