C# 更有效的文件下载代码

     前几天在asp.net专栏中看到一篇关于更有效的文件下载内容的文章,觉得很好,正好自己也要用到这些代码,就把他原文中用VB写的代码转化成c#的了,贴出来给大家分享一下!

1.普通下载:

         // 下载文件的路径
         string  path = Server.MapPath( " 广告.jpg " );
        
// 下载文件的名称
         string  filename  =   " 广告.jpg " ;
        System.IO.FileInfo toDownload 
=   new  System.IO.FileInfo(path);
        Response.Clear();
        
if  (System.IO.Path.GetExtension(filename)  ==   " .jpg " )
        
{
            Response.AddHeader(
"Content-Disposition""attachment;filename=NEW_" + HttpUtility.UrlEncode(toDownload.Name));
            Response.ContentType 
= "application/x-zip-compressed";
            Response.TransmitFile(path);
            Response.End();
        }

2.大文件分成小块下载:

         // 下载文件的路径
         string  path  =  Server.MapPath( " 广告.jpg " );
        
// 下载文件的名称
         string  filename  =   " 广告.jpg " ;
        System.IO.FileInfo toDownload 
=   new  System.IO.FileInfo(path);

        
if  (toDownload.Exists  ==   true )
        
{
            
const long ChunkSize = 10000;
            
byte[] buffer = new byte[ChunkSize];

            Response.Clear();
            System.IO.FileStream iStream 
= System.IO.File.OpenRead(path);
            
long dataLengthToRead = iStream.Length;
            Response.ContentType 
= "application/octet-stream";
            Response.AddHeader(
"Content-Disposition""attachment; filename=new_" + HttpUtility.UrlEncode(toDownload.Name));
            
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();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值