超链接 下载TEXT文件,而不是直接在IE中打开

王朝学院·作者佚名  2016-05-21
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航