views:

508

answers:

2

I've following code for file download:

        FileInfo fileInfo = new FileInfo(filePath);

        context.Response.Clear();
        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(filePath));
        context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
        context.Response.WriteFile(filePath);
        context.Response.End();

When I run it on my local IIS6 it works fine. Web browser (tested on IE8, Firefox 3.5.2, Opera 10) shows file length before I start download the file.

When I run this code on remote IIS7, web browser doesn't shows file length. File length is unknown.

Why I don't get file length when this code runs under IIS7?

+2  A: 

Use Fiddler to check what is actually sent. My guess is you are getting chunked encoding as a result of buffering being set to false on the IIS7 server.

BTW, drop the Response.End call its quite a traumatic thing to do and is unnecessary (for that matter so is the call to Clear).

Edit

Strictly speaking when streaming content with chunked encoding (which is desirable in your scenario) the Content-Length header ought not be present (see RFC2616 Section 4.4.) It seems to me that IIS7 takes it upon itself to enforce this. In fact I've had a Classic-ASP scenario in which IIS7 throws an error when COM code tries to add a Content-Length header when buffering is off.

This is really annoying because despite what the committee in the ivory towers would like, this header give the end user a very useful piece of info.

AnthonyWJones
Yes, I'm getting "transfer-encoding: chunked" and Content-Length is not returned. Is any way to get Content-Length in response header? I don't have direct access to IIS7 server.
GTD
A: 

Thanks for this post.... I got it working for IE with the first line.

public void WriteCSV(string strData) {
   //Required for IIs7 WS2008R2 fix
   Response.ClearHeaders();
   Response.Clear();


   Response.Buffer = true; 
   Response.ContentType = "application/csv";
   Response.AddHeader("Content-Disposition", "attachment;filename=report.csv");
   Response.Write(strData);
   Response.Flush();
   Response.End();
}
Rich