Tôi đang sử dụng Filestream để đọc tệp lớn (> 500 MB) và tôi nhận được OutOfMemoryException.OutOfMemoryException khi tôi đọc 500MB FileStream
Bất kỳ giải pháp nào về nó.
Mã của tôi là:
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;
}
Xin vui lòng, đó là mã tốt nhất, tôi sử dụng: http://www.yoda.arachsys.com/csharp/readbinary.html Cảm ơn mister –
+1: Có, phân bổ kích thước bộ đệm bạn cần là một ý tưởng hay ... thực sự, tôi ngạc nhiên rằng .NET không có phương thức để đọc toàn bộ tập tin vào một mảng byte hoặc một số cấu trúc tương tự khác. – Powerlord
. File.ReadAllBytes http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx Nhưng đó không phải là những gì poster này nên làm. Đọc tất cả các byte của một tập tin 500MB vào bộ nhớ là * thường là một ý tưởng tồi *, và trong trường hợp này, ... đó là một ý tưởng rất tồi. Các poster rõ ràng có trong tâm trí một mục tiêu chính, chưa unstated đó không phải là "đọc tất cả các byte của một tập tin vào bộ nhớ." Anh * nghĩ * anh ta cần đọc tất cả các byte, nhưng điều đó không đúng. – Cheeso