知识在于积累(.NET之路……)

导航

C#之文件下载

string path="/Dir/01.txt"; //文件相对路径
string Files = Server.MapPath(path);
if (File.Exists(Files))
{
try
{
System.IO.FileInfo DownloadFile = new System.IO.FileInfo(Files);
string fileName = DownloadFile.Name;
System.Web.HttpContext context = System.Web.HttpContext.Current;
Response.Clear();
Response.ClearHeaders();
Response.Buffer = false;
Response.ContentType = "application/octet-stream ";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + context.Server.UrlEncode(String.Format("{0}", fileName)) + "\"");
Response.AddHeader("Content-Length", DownloadFile.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(Files);
Response.Flush();
Response.End();
}
catch
{
lblinfo.Text
= "无法找到该文件!文件可能已经被移动或者删除。";
}
}

posted on 2010-10-25 11:08  汤尼  阅读(151)  评论(0编辑  收藏  举报