C# ASP.NET 3.5 content-disposition file download problems

John Batdorf picture John Batdorf · Dec 3, 2008 · Viewed 17.5k times · Source

I have a sql database that stores some documents.

A user can sign into the application, and view a list of their documents.

When clicking a linkbutton download in a gridview of their docs, I get the file from the database, write it to the file system, and then execute this code.

    System.IO.FileInfo file = new System.IO.FileInfo(System.Configuration.ConfigurationManager.AppSettings["UploadPath"] + DocumentName);

    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Cookies.Clear();
    Response.Cache.SetCacheability(HttpCacheability.Private);
    Response.CacheControl = "private";
    Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
    Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
    Response.AppendHeader("Content-Length", file.Length.ToString());
    Response.AppendHeader("Pragma","cache");
    Response.AppendHeader("Expires", "60");
    Response.ContentType = GetContentType(file.Extension);
    Response.AppendHeader("Content-Disposition",
    "inline; " +
    "filename=\"" + file.Name + "\"; " +
    "size=" + file.Length.ToString() + "; " +
    "creation-date=" + DateTime.Now.ToString("R") + "; " +
    "modification-date=" + DateTime.Now.ToString("R") + "; " +
    "read-date=" + DateTime.Now.ToString("R"));

My GetContentType() method just returns the appropriate file type for the files I'm allowing "application/pdf, application/msw0rd, etc.

My problem is that when the file gets saved, it's the webpage itself, not the file from the file system. And in google chrome, it's putting a .htm extension on the end of the filename, I guess because it knows it's a web page?

Anyhow, a great first step would be to get the actual file, and not a copy of the web page in HTML they are sitting on!

Thanks.

Answer

Samiksha picture Samiksha · Dec 3, 2008

Instead of

Response.AppendHeader("Content-Disposition", "inline; " + "filename=

use

Response.AddHeader("content-disposition:", "attachment;filename=