English 中文(简体)
系统。 在上传大型文件时, 将模拟例外的输出丢弃到系统上 。
原标题: System.OutOfMemoryException was thrown while uploading large file

当我上传超过500 MB 的文件时, 我就会跟踪错误

"除类型系统外,还抛出除去记忆外的例外。 "

我的代码显示如下:

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);
}
问题回答

不要试图同时读取整个溪流。 反正你也不会同时读取整个溪流。

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

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

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





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签