C#文件下载四种方法

从CSDN论坛上看到这个帖子:

 http://topic.csdn.net/u/20120822/10/d8115bb7-2f2a-4c2f-b0c1-aab68bcb1e3e.html

出于对C#功能的好奇,想那个工程试看看。

 

一、过程

1、建C# Form工程

以前接触的都是C# Form工程,以为这次也一样,没想到到报以下错误:

名空间“System.Web”中不存在类型或命名空间名称“UI”(是缺少程序集引用吗?)

既然这样,我就在引用里加入System.Configuration.dll及System.web。

但这次报别一个错了:

 错误 CS0103: 当前上下文中不存在名称“Respone”
C:\Documents and Settings\Administrator\桌面\CShartDownLoad\Form1.cs(34,13): 错误 CS0103: 当前上下文中不存在名称“Response”
C:\Documents and Settings\Administrator\桌面\CShartDownLoad\Form1.cs(35,31): 错误 CS0103: 当前上下文中不存在名称“Server”
C:\Documents and Settings\Administrator\桌面\CShartDownLoad\Form1.cs(36,13): 错误 CS0103: 当前上下文中不存在名称“Response”

后来上网才知道,是我建的工程类型错了。

2、建C# Web工程

添加论坛中的代码,编译报错:

C:\Documents and Settings\Administrator\桌面\CSharpDownLoad\Default.aspx.cs(40,13): 错误 CS0246: 找不到类型或命名空间名称“FileInfo”(是否缺少 using 指令或程序集引用?)
C:\Documents and Settings\Administrator\桌面\CSharpDownLoad\Default.aspx.cs(40,37): 错误 CS0246: 找不到类型或命名空间名称“FileInfo”(是否缺少 using 指令或程序集引用?)
C:\Documents and Settings\Administrator\桌面\CSharpDownLoad\Default.aspx.cs(91,13): 错误 CS0246: 找不到类型或命名空间名称“FileStream”(是否缺少 using 指令或程序集引用?)
C:\Documents and Settings\Administrator\桌面\CSharpDownLoad\Default.aspx.cs(91,33): 错误 CS0246: 找不到类型或命名空间名称“FileStream”(是否缺少 using 指令或程序集引用?)
C:\Documents and Settings\Administrator\桌面\CSharpDownLoad\Default.aspx.cs(91,54): 错误 CS0103: 当前上下文中不存在名称“FileMode”

解决方法是 添加引用头文件:

using System.IO;


==== ^-^  ===  哈,终于编译通过了。

3、测试

在网站文件中添加

<div>
    <asp:Button ID="Button1" runat="server" Text="法一"  OnClick="Button1_Click"/>
    <asp:Button ID="Button2" runat="server" Text="法二"  OnClick="Button2_Click"/>
    <asp:Button ID="Button3" runat="server" Text="法三"  OnClick="Button3_Click"/>
    <asp:Button ID="Button4" runat="server" Text="法四"  OnClick="Button4_Click"/>
    </div>


 

4、源码讲解

  法一:

// 法一:TransmitFile实现下载
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.ContentType = "application/x-zip-compressed";
            Response.AddHeader("Content-Disposition", "attachment;filename=z.zip");
            string filename = Server.MapPath("DownLoad/z.zip");
            Response.TransmitFile(filename);
        }

ContentType 属性指定响应的 HTTP 内容类型。如果未指定 ContentType,默认为 text/HTML

语法 Response.ContentType [= ContentType ] 参数 ContentType 描述内容类型的字符串。该字符串通常被格式化为类型/子类型,其中类型是常规内容范畴而子类为特定内容类型。

法二:

  // 法二:WriteFile实现下载
        protected void Button2_Click(object sender, EventArgs e)
        {
            string fileName = "asd.txt";//客户端保存的文件名
            string filePath = Server.MapPath("DownLoad/aaa.txt");//路径

            FileInfo fileInfo = new FileInfo(filePath);
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.AddHeader("Content-Length", fileInfo.Length.ToString());
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.ContentType = "application/octet-stream";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.WriteFile(fileInfo.FullName);
            Response.Flush();
            Response.End();
        }

 

response.write的意思是返回一个消息给其它页面也可以,当前页面也行的。

法三:

 // 法三:WriteFile分块下载
        protected void Button3_Click(object sender, EventArgs e)
        {
            string fileName = "aaa.txt";//客户端保存的文件名
            string filePath = Server.MapPath("DownLoad/aaa.txt");//路径

            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);

            if (fileInfo.Exists == true)
            {
                const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
                byte[] buffer = new byte[ChunkSize];

                Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
                long dataLengthToRead = iStream.Length;//获取下载的文件总大小
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
                while (dataLengthToRead > 0 && Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
                    Response.OutputStream.Write(buffer, 0, lengthRead);
                    Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                Response.Close();
            }
        }


法四:

// 法四:流方式下载
        protected void Button4_Click(object sender, EventArgs e)
        {
            string fileName = "aaa.txt";//客户端保存的文件名
            string filePath = Server.MapPath("DownLoad/aaa.txt");//路径

            //以字符流的形式下载文件
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();

        }


 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值