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

转载于:https://www.cnblogs.com/xiaoyintao/p/4056297.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值