The error indicates that you ran out of memory while trying to allocate a 1 GB byte array in memory. This is not related to MVC. It should also be noted that the memory limit for 32-bit processes is 2 GB. If your server has a 32-bit OS installed and you allocate 1 GB for one boot, you will quickly run out of available memory.
Instead of trying to read the entire stream in memory, use Stream.Read to read data in chuncks using a buffer of sufficient size and store chuncks in the file stream by calling Write. You not only avoid OutOfMemoryExceptions, but your code will work much faster, because you do not have to wait until only 1 GB to load before storing it in a file.
The code may be simple:
public static void SaveStream(Stream st,string targetFile) { byte[] inBuffer = new byte[10000]; using(FileStream outStream=File.Create(targetFile,20000)) using (BinaryWriter wr = new BinaryWriter(outStream)) { st.Read(inBuffer, 0, inBuffer.Length); wr.Write(inBuffer); } }
You can adjust the buffer sizes to balance bandwidth (how fast you load and save) and scalability (how many clients you can handle).
source share