tags:

views:

1217

answers:

5

I am having problem with writing PDF files to browser. Other mime types work fine. PDF files become corrupted.

        FileInfo file = new FileInfo(Path.Combine(_module.FileDir, _file.FilePath));
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = _file.ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Regex.Replace(_file.FilePath, "\\s", "-"));
        Response.AppendHeader("Content-Length", file.Length.ToString());
        try
        {
            Response.WriteFile(file.FullName);
            Response.Flush();
            Response.Close();
        }
        catch
        {
            Response.ClearContent();
        }
A: 

For this situation, a Response.Redirect should work just as well:

FileInfo file = new FileInfo(Path.Combine(_module.FileDir, _file.FilePath));
Response.Redirect(file.FullName);
Gordon Bell
I'm assuming the OP doesn't want to have directly-downloadable content, perhaps via some authentication mechanism or some such. Response.Redirect would expose the URL, whereas OP's technique (and Microsoft's, in my response) would allow the content to come from anywhere the IIS context user could access on the web server, thus potentially protecting it more. (Yes, I'm the king of run-on sentences.)
John Rudy
Good advice. I will redirect request to avoid HTTP Module to kick in
A: 
  1. Are you sure you're getting the right MIME type?
  2. Are you attempting to force the user to download, or just stream out the PDF data?
  3. Are you performing a Response.End() call anywhere to ensure that no extra data (outside of the headers and the PDF binary) is sent?

I'm thinking it's #3 that may be your issue here. Microsoft's Knowledge Base provides this code to do, essentially, what you seem to be doing.

//Set the appropriate ContentType.
Response.ContentType = "Application/pdf";
//Get the physical path to the file.
string FilePath = MapPath("acrobat.pdf");
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();
John Rudy
+1  A: 

My problem was with HTTP Module. I was applying White space filter

    HttpApplication app = sender as HttpApplication;
    if (app != null && app.Request.RawUrl.Contains(".aspx"))
    {
        app.Response.Filter = new WhitespaceFilter(app.Response.Filter);
    }
+1  A: 

IIS HTTP Compression and Streaming PDF's: Don't work well. http://blog.1530technologies.com/2006/11/iis_http_compre.html

A: 

You need these three statements:

Response.Flush(); Response.Close(); Response.End();

The last one is the most important.

John Lamber
Response.Flush(); Response.Close(); same as Response.End(); Response.End(); does both things