C# DownloadFile

public void DownloadFile(string dowloadFilePath)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Expires = 0;
        System.IO.FileStream _streamReader = System.IO.File.OpenRead(dowloadFilePath);
        int _count = 0;
        byte[] _bytes = null;

        string _strFilename = "";
        _strFilename = dowloadFilePath.Substring(dowloadFilePath.LastIndexOf("\\") + 1);

        Response.ContentType = "octet-stream";
        Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(_strFilename));

        try
        {
            int maxLengthPerPackage = 1024 * 1024;
            long FileLength = _streamReader.Length;
            if (FileLength <= maxLengthPerPackage)
            {
                _bytes = new byte[FileLength];
                _streamReader.Read(_bytes, 0, (int)(FileLength)); // 读取文件内容
                Response.BinaryWrite(_bytes);
                Response.Flush();
            }
            else
            {
                //当文件大于1M时,分段读文件,以防死机
                for (int i = 0; i <= FileLength / maxLengthPerPackage; i++)
                {
                    if (FileLength - (i * maxLengthPerPackage) > maxLengthPerPackage)
                        _bytes = new byte[maxLengthPerPackage];
                    else
                        _bytes = new byte[FileLength % maxLengthPerPackage];
                    int canReadLength = _streamReader.Read(_bytes, 0, _bytes.Length); // 读取文件内容
                    _count += canReadLength;
                    Response.BinaryWrite(_bytes);
                    Response.Flush();
                }
            }
        }
        //分段读文件,以防死机
        finally
        {
            if (_streamReader != null)
            {
                _streamReader.Close();
                //System.IO.File.Delete(dowloadFilePath);   //delete output tempary file
            }
        }

        Response.End();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值