This example illustrates a simple technique to download files of any type from you web application to the client browser. In addition to setting the MIME types, the example shows how to force the Download File dialog that allows the user to either run or save the file, even if the file type would normally display in the browser's window.
protected void lnkDownloadSample_Click(object sender, EventArgs e)
{DownloadFile("SampleCSV/AddressBook.csv", true);
}
private void DownloadFile(string fname, bool forceDownload)
{
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
case ".csv":
case ".xls":
type = "Application/x-msexcel";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + name);
}
if (type != "")
Response.ContentType = type;
Response.WriteFile(path);
Response.End();
}
}
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
case ".csv":
case ".xls":
type = "Application/x-msexcel";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + name);
}
if (type != "")
Response.ContentType = type;
Response.WriteFile(path);
Response.End();
}
}
No comments:
Post a Comment