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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。