通常的文件下载是用跳出窗口实现的,但是有个问题,就是会被广告拦截软件直接拦截掉,另我非常的头痛,于是寻找更好的解决方法.看了用Response.BinaryWrite写文件流一文之后觉得确实可以如此。
    如下代码实现了此功能,解决了文件格式问题(就是只将流输出,但无法正确识别文件格式),并且从注册表读取文件的ContentType

1 /**//// <summary>
2 /// 下载文件
3 /// </summary>
4 /// <param name="filename">文件物理地址</param>
5 protected void DownloadFile(string filename)
6 {
7
8 string saveFileName = "test.xls";
9 int intStart = filename.LastIndexOf("//")+1;
10 saveFileName = filename.Substring(intStart,filename.Length-intStart);
11
12 System.IO.FileInfo fi=new System.IO.FileInfo(filename);
13 string fileextname=fi.Extension;
14 string DEFAULT_CONTENT_TYPE = "application/unknown";
15 RegistryKey regkey,fileextkey;
16 string filecontenttype;
17 try
18 {
19 regkey=Registry.ClassesRoot;
20 fileextkey=regkey.OpenSubKey(fileextname);
21 filecontenttype=fileextkey.GetValue("Content Type",DEFAULT_CONTENT_TYPE).ToString();
22 }
23 catch
24 {
25 filecontenttype=DEFAULT_CONTENT_TYPE;
26 }
27
28
29 Response.Clear();
30 Response.Charset = "utf-8";
31 Response.Buffer= true;
32 this.EnableViewState = false;
33 Response.ContentEncoding = System.Text.Encoding.UTF8;
34
35 Response.AppendHeader("Content-Disposition","attachment;filename=" + saveFileName);
36 Response.ContentType=filecontenttype;
37
38 Response.WriteFile(filename);
39 Response.Flush();
40 Response.Close();
41
42 Response.End();
43 }

效果图如下:

 

本文转载:CSDN博客