·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> asp.net 超链接 下载TEXT文件,而不是直接在IE中打开
问题描述:后台生成了文本文件,用超链接提供给用户下载。点击超链接,下载Excel文件没问题,但文本文件会直接被打开,而不是弹出下载窗口。
解决方法:把HyperLink改为LinkButton,在Click事件中,用文件流写文本文件。
关键代码:
1 PRotected void Button1_Click(object sender, EventArgs e) 2 { 3 string sFileName = System.IO.Path.GetRandomFileName(); 4 string sGenName = "Friendly.txt"; 5 6 //YOu could omit these lines here as you may 7 //not want to save the textfile to the server 8 //I have just left them here to demonstrate that you could create the text file 9 using (System.IO.StreamWriter SW = new System.IO.StreamWriter(10 Server.MapPath("TextFiles/" + sFileName + ".txt")))11 {12 SW.WriteLine(txtText.Text);13 SW.Close();14 }15 16 System.IO.FileStream fs = null;17 fs = System.IO.File.Open(Server.MapPath("TextFiles/" + 18 sFileName + ".txt"), System.IO.FileMode.Open);19 byte[] btFile = new byte[fs.Length];20 fs.Read(btFile, 0, Convert.ToInt32(fs.Length));21 fs.Close();22 Response.AddHeader("Content-disposition", "attachment; filename=" + 23 sGenName);24 Response.ContentType = "application/octet-stream";25 Response.BinaryWrite(btFile);26 Response.End();27 }
参考文档:http://www.codeproject.com/useritems/textfile.asp