1

I get following error when i upload files larger than 500 MB

"Exception of type 'System.OutOfMemoryException' was thrown. "

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);
}
ravidev
  • 2,708
  • 6
  • 26
  • 42

2 Answers2

4

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;
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • I think some [pseudo-]code is missing about "store the ... bytes". (Also, is there a particular reason for `offset`?) –  May 23 '12 at 07:34
  • @pst: I clarified the comment. The `offset` variable isn't used by the code here, but it might be needed by the code that should store the data. – Guffa May 23 '12 at 08:14
  • @Guffa : how can i store bytes of buffer in your code..can you please specify it? – ravidev May 23 '12 at 08:30
  • @ravidev "Write to file" or as appropriate. –  May 23 '12 at 08:35
  • @Guffa : i tried your code and also tried with following link : http://stackoverflow.com/questions/221925/creating-a-byte-array-from-a-stream but i got same message "System.OutOfMemoryException" – ravidev May 23 '12 at 09:01
0

You should not load the entire file into a byte array. Instead, you can process the file directly from the input stream.

Marek Dzikiewicz
  • 2,844
  • 1
  • 22
  • 24