c#下载服务器文件夹目录下的文件

时间:2021-01-29 12:31:26

首先,在Page_Load事件中添加如下代码:

LinkButton l = new LinkButton();
l.Text = "点此下载文件" ;
l.ToolTip = 文件名
l.Font.Bold = true;
l.Click += new EventHandler(l_Click);
this.PlaceHolder1.Controls.Add(l);

接下来,实现Click 事件:

void l_Click(object sender, EventArgs e)
{
LinkButton l = sender as LinkButton;
string filePath = Server.MapPath("~/UpLoad") + "//" + l.ToolTip;
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
if (file.Exists)
{
Response.Clear();

Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();

Response.WriteFile(file.FullName);
Response.End();
}

}