user81740
user81740

Reputation: 233

Response.WriteFile PDF files - corrupted files

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();
}

Upvotes: 1

Views: 8100

Answers (5)

John Lamber
John Lamber

Reputation: 281

You need these three statements:

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

The last one is the most important.

Upvotes: 1

user81740
user81740

Reputation: 233

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

Upvotes: 1

user81740
user81740

Reputation: 233

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);
    }

Upvotes: 1

John Rudy
John Rudy

Reputation: 37858

  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();

Upvotes: 0

Gordon Bell
Gordon Bell

Reputation: 13633

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);

Upvotes: 0

Related Questions