【问题标题】:'System.OutOfMemoryException' was thrown while uploading large file上传大文件时抛出“System.OutOfMemoryException”
【发布时间】:2012-05-23 07:18:09
【问题描述】:

上传大于 500 MB 的文件时出现以下错误

“抛出了‘System.OutOfMemoryException’类型的异常。”

我的代码如下所示:

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);
}

【问题讨论】:

  • 简单地说,您正在创建一个字节数组,它对于您的机器来说太大而无法在内存中处理。
  • file.InputStream.Length 的值是多少?
  • @FurDworetzky:相反,这个问题更好。
  • @RoyiNamir:我没有得到正确的答案。我该如何接受?

标签: c# asp.net file-upload


【解决方案1】:

不要试图一次读取整个流。无论如何,您不会一次获得整个流。

创建一个大小合理的缓冲区,然后一次读取一个块:

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;
}

【讨论】:

  • 我认为缺少一些关于“存储 ... 字节”的 [伪] 代码。 (另外,offset 有什么特别的原因吗?)
  • @pst:我澄清了评论。 offset 变量没有被此处的代码使用,但应该存储数据的代码可能需要它。
  • @Guffa : 我怎样才能在你的代码中存储缓冲区字节......你能指定它吗?
  • @ravidev "写入文件" 或视情况而定。
  • @Guffa :我尝试了您的代码并尝试了以下链接:stackoverflow.com/questions/221925/… 但我收到了相同的消息“System.OutOfMemoryException”
【解决方案2】:

您不应将整个文件加载到字节数组中。相反,您可以直接从输入流中处理文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-30
    • 2016-05-05
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多