我正在使用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