天若有情.NET

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

ASP.NET 中直接下载文件的方法代码:

// 文件的名称
string filename = Server.MapPath("~/test.txt");

   System.IO.FileInfo aFile = new System.IO.FileInfo(filename);
   string na=Path.GetFileName(name);
   Response.Clear();
   Response.ClearHeaders();
   Response.BufferOutput=false;
   Response.ContentType="application/octet-stream";
   //Response.AddHeader("Content-Disposition","attachment;filename="+na);
   //上面这条中文会乱码,应该下面这样写
   Response.AppendHeader("Content-disposition","attachment;filename=" + HttpUtility.UrlEncode(na,System.Text.Encoding.UTF8));
   Response.AddHeader("Content-Length",aFile.Length.ToString());
   Response.WriteFile(name);
   Response.Flush();
   Response.End();

此代码,我已经在实际项目中多次使用,很方便的,收藏吧。

posted on 2005-01-27 10:39  pathik  阅读(567)  评论(0)    收藏  举报