[英]'System.OutOfMemoryException' was thrown while uploading large file
I get following error when i upload files larger than 500 MB 当我上传大于500 MB的文件时,我收到以下错误
"Exception of type 'System.OutOfMemoryException' was thrown. " “抛出了'System.OutOfMemoryException'类型的异常。”
My code is shown below: 我的代码如下所示:
public readonly string Filename, ContentType;
public readonly int Size;
public readonly byte[] Bytes;
public FileHolder(HttpPostedFile file)
{
Filename = Path.GetFileName(file.FileName);
ContentType = GetContentType(file.ContentType, Filename);
Size = file.ContentLength;
Bytes = new byte[file.InputStream.Length]; //Here i get error
file.InputStream.Read(Bytes, 0, Size);
}
Don't try to read the entire stream all at once. 不要试图一次读取整个流。 You won't get the entire stream all at once anyway.
无论如何,你不会同时获得整个流。
Create a buffer with a reasonable size, then read a block at a time: 创建一个合理大小的缓冲区,然后一次读取一个块:
byte[] buffer = new byte[8192];
int offset = 0;
int left = Size;
while (left > 0) {
int len = file.InputStream.Read(buffer, 0, Math.Min(buffer.Length, left));
left -= len;
// here you should store the first "len" bytes of the buffer
offset += len;
}
You should not load the entire file into a byte array. 您不应将整个文件加载到字节数组中。 Instead, you can process the file directly from the input stream.
相反,您可以直接从输入流处理文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.