首页 > Web开发 > 详细

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

时间:2014-10-28 12:00:30      阅读:486      评论:0      收藏:0      [点我收藏+]

问题描述:后台生成了文本文件,用超链接提供给用户下载。点击超链接,下载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

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

原文:http://www.cnblogs.com/xiaoyintao/p/4056297.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!