views:

120

answers:

1

Hi,

An user posts this article about how to use HttpResponse.Filter to compress large amounts of data. But what will happen if I try to transfer a 4G file? will it load the whole file in memory in order to compress it? or otherwise it will compress it chunk by chunk?

I mean, I'm doing this right now:

        public void GetFile(HttpResponse response)
    {
        String fileName = "example.iso";
        response.ClearHeaders();
        response.ClearContent();
        response.ContentType = "application/octet-stream";
        response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.AppendHeader("Content-Length", new FileInfo(fileName).Length.ToString());
        using (FileStream fs = new FileStream(Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), fileName), FileMode.Open))
        using (DeflateStream ds = new DeflateStream(fs,CompressionMode.Compress))
        {
            Byte[] buffer = new Byte[4096];
            Int32 readed = 0;

            while ((readed = ds.Read(buffer, 0, buffer.Length)) > 0)
            {
                response.OutputStream.Write(buffer, 0, readed);
                response.Flush();
            }
        }
    }

So at the same time I'm reading, I'm compressing and sending it. Then I wanna know if HttpResponse.Filter do the same thing, or otherwise it will load the whole file in memory in order to compress it.

Also, I'm a little bit insecure about this... maybe is needed to load the whole file in memory to compress it... is it?

Cheers.

+2  A: 

HttpResponse.Filter is a stream: You can write in it in chunks.

You are doing it correctly. You are using FileStream and DeflateStream to read from file and compress it. You are reading 4096 bytes at time and then writing them into the Response Stream. So all you are using is 4096 byte(and a little bit more) of memory.

cornerback84
I know I can write in chunks, but my question is... will it send it also chunk by chunk? or otherwise will it wait to have the whole stream loaded to compress it and then send it?
vtortola
Then it won't be a 'Stream'. The response is streamed to the destination as you write in the Response Stream. It will only be kept in memory while it is being sent over the network. Deflate stream will not read the whole File as it is using FileStream to read from file in chunks(4096 bytes).
cornerback84
thanks a lot! :)
vtortola