简体   繁体   English

上传大文件时抛出'System.OutOfMemoryException'

[英]'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.

相关问题 上传Blob时抛出了类型'System.OutOfMemoryException'的异常 - Exception of type 'System.OutOfMemoryException' was thrown while uploading Blob 读取大文件-System.OutOfMemoryException:引发了类型为'System.OutOfMemoryException'的异常。 在C#中 - Reading large file - System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown. in C# ZipArchive中针对URL中的大文件引发了“ System.OutOfMemoryException” - 'System.OutOfMemoryException' was thrown in ZipArchive for large file from URL 在EF中为大表抛出System.OutOfMemoryException - System.OutOfMemoryException thrown for large table in EF 引发了“ System.OutOfMemoryException” - 'System.OutOfMemoryException' was thrown 填充大文件时出现PDFClown System.OutOfMemoryException - PDFClown System.OutOfMemoryException while populating large file 使用大列表时出现System.OutOfMemoryException - System.OutOfMemoryException while working with large Lists 异常:抛出 System.OutOfMemoryException - Exception: System.OutOfMemoryException was thrown 在仍有空闲VM空间的情况下抛出System.OutOfMemoryException - System.OutOfMemoryException is thrown while still having free VM space “使用xmlserializer时抛出了类型'System.OutOfMemoryException'的异常 - “Exception of type 'System.OutOfMemoryException' was thrown” while using xmlserializer
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM