asp.net中的下载实现

我现在接触到的下载有两种形式:
直接下载服务器某个目录下的文件和下载数据库中存的二进制文件

代码如下:
//获取文件对象
FileInfo file = new FileInfo(Server.MapPath("~/123123213213.txt"));

//附件形式
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("好啊.txt", System.Text.Encoding.UTF8));
Response.WriteFile(file.FullName);
           

//模拟数据库取出的二进制流形式
Response.Clear();
byte[] b = new byte[file.Length];
FileStream fs = new FileStream(Server.MapPath("~/123123213213.txt"), FileMode.Open);
fs.Read(b, 0, (int)file.Length);//这里强转,存时要限制流大小
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("好啊.txt", System.Text.Encoding.UTF8));
Response.BinaryWrite(b);

有几点需要说明:
1.Content-Disposition是一种扩展的html协议,我的理解是正好可以来处理下载功能
他的值有两种:attachment表示以附件形式下载,inline表示就在网页上来显示
2.filename后面可以自己跟据需要来定文件名与文件扩展名
3.如果文件名内有中文字,一定要编码,不然会有乱码的

一面是一个比较好的网址,说的比我详细:
http://www.cnblogs.com/fredlau/archive/2008/10/14/1311018.html
原文地址:https://www.cnblogs.com/ljzforever/p/1434815.html