文件下载 asp.net相关代码,只要知道需要下载的文件路径。。。


///<summary>
/// Download File
/// </summary>
/// <param name="filename">the path of file</param>
protected void DownloadFile(string filename)
{
string saveFileName = "test.txt";
int intStart = filename.LastIndexOf("\\") + 1;
saveFileName = filename.Substring(intStart, filename.Length - intStart);
System.IO.FileInfo fi = new System.IO.FileInfo(filename);
string fileextname = fi.Extension;
string DEFAULT_CONTENT_TYPE = "application/unknown";
RegistryKey regkey, fileextkey;
string filecontenttype;
try
{
regkey = Registry.ClassesRoot;
fileextkey = regkey.OpenSubKey(fileextname);
filecontenttype = fileextkey.GetValue("Content Type", DEFAULT_CONTENT_TYPE).ToString();
}
catch
{
filecontenttype = DEFAULT_CONTENT_TYPE;
}
Response.Clear();
Response.Charset = "utf-8";
Response.Buffer = true;
this.EnableViewState = false;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + saveFileName);
Response.ContentType = filecontenttype;
Response.WriteFile(filename);
Response.Flush();
Response.Close();
Response.End();
}
/// Download File
/// </summary>
/// <param name="filename">the path of file</param>
protected void DownloadFile(string filename)
{
string saveFileName = "test.txt";
int intStart = filename.LastIndexOf("\\") + 1;
saveFileName = filename.Substring(intStart, filename.Length - intStart);
System.IO.FileInfo fi = new System.IO.FileInfo(filename);
string fileextname = fi.Extension;
string DEFAULT_CONTENT_TYPE = "application/unknown";
RegistryKey regkey, fileextkey;
string filecontenttype;
try
{
regkey = Registry.ClassesRoot;
fileextkey = regkey.OpenSubKey(fileextname);
filecontenttype = fileextkey.GetValue("Content Type", DEFAULT_CONTENT_TYPE).ToString();
}
catch
{
filecontenttype = DEFAULT_CONTENT_TYPE;
}
Response.Clear();
Response.Charset = "utf-8";
Response.Buffer = true;
this.EnableViewState = false;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + saveFileName);
Response.ContentType = filecontenttype;
Response.WriteFile(filename);
Response.Flush();
Response.Close();
Response.End();
}