0

The following code works well with small files, like 100MB, but it throws a System.OutOfMemoryException for bigger files, like 400MB. I'm using the NotNetZip as dll to get file as zip.

This is my code:

string pathGetDoc = pathDocs + "\\" + informe.NickName + "\\" + getMesActual() + "\\" + informe.Name;

string fileName = informe.Name;

System.Net.WebClient wc = new System.Net.WebClient();
wc.OpenRead(pathGetDoc);
int bytes_total = Convert.ToInt32(wc.ResponseHeaders["Content-Length"].ToString());

if(bytes_total >= 100000000)
{
    using (ZipFile zip = new ZipFile())
    {
        zip.AddFile(pathGetDoc, fileName);
        zip.CompressionMethod = CompressionMethod.BZip2;
        zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
        using (MemoryStream memoryStream = new MemoryStream())
        {
            zip.Save(memoryStream);
            return File(memoryStream.ToArray(), "application/zip", "z.zip");
        }
    }
}

As you can see, I have a IF to check the size of the file, this work good but when the process goes to save .zip file, I have the error System.OutOfMemoryException

Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
  • 1
    The problem happens when you use `memoryStream.ToArray()` (apparently, that server has way too little RAM). Don't use `memoryStream.ToArray()`, use just `memoryStream` for streaming the result – Camilo Terevinto Apr 26 '19 at 23:26
  • As suggested if the server is that tight for memory the best solution is to stream the data directly to the response stream. Check out https://learn.microsoft.com/en-us/dotnet/api/system.web.mvc.filestreamresult?view=aspnet-mvc-5.2 and https://stackoverflow.com/questions/7163448/mvc-controller-using-response-stream – Jamie Gould Apr 27 '19 at 01:22
  • Hi friend I try without .array() and WebClient(downloadfile) but do not work, is the same result System.outofmemoryExeption – lord_manuel Apr 29 '19 at 22:56

0 Answers0