C#中使用HttpDownLoadHelper下载文件实例

作者:shichen2014 时间:2023-05-13 13:13:14 

本文实例讲述了C#使用HttpDownLoadHelper下载文件的方法。分享给大家供大家参考。具体实现方法如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Threading;

namespace ProjectWenDangManage.Framework
{
    /// <summary>
    /// HTTP文件下载辅助类
    /// </summary>
    public class HttpDownLoadHelper
    {
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="_Request"></param>
        /// <param name="_Response"></param>
        /// <param name="_fileName">下载文件时的短文件名称</param>
        /// <param name="_fullPath">待下载文件的绝对路径</param>
        /// <param name="_speed">下载速度</param>
        /// <returns></returns>
        public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
        {
            try
            {
                FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    double pack = 10240; //10K bytes
                    //int sleep = 200;   //每秒5次   即5*10K bytes每秒
                    int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        //Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                            Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();

                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
        }
    }
}

HttpDownLoadHelper

在webfrom中:

string filePath=Path.Combine(HttpRuntime.AppDomainAppPath,"Files","项目管理工具.msi");
HttpDownLoadHelper.ResponseFile(Request, Response, "下载显示的名称", filePath, 102400);

在mvc中:

string filePath=Path.Combine(HttpRuntime.AppDomainAppPath,"Files","项目管理工具.msi");
HttpDownLoadHelper.ResponseFile(HttpContext.ApplicationInstance.Context.Request, HttpContext.ApplicationInstance.Context.Response, "下载显示的名称", filePath, 102400);

希望本文所述对大家的C#程序设计有所帮助。

标签:C#,下载,文件
0
投稿

猜你喜欢

  • 流式图表拒绝增删改查之kafka核心消费逻辑上篇

    2023-04-19 03:32:11
  • 源码剖析Android中Okio的使用

    2023-07-03 20:48:44
  • SpringBoot中配置SSL的同时支持http和https访问

    2022-06-30 00:58:58
  • android开发教程之自定义属性用法详解

    2022-09-22 20:26:17
  • c#使用S22.Imap收剑灵激活码邮件代码示例(imap收邮件)

    2022-11-27 20:59:37
  • 解决Spring Cloud Feign 请求时附带请求头的问题

    2022-12-11 04:29:46
  • c语言中static修饰函数的方法及代码

    2023-08-26 15:46:21
  • Android IPC机制Messenger实例详解

    2023-04-27 13:25:06
  • Android实现Tab切换界面功能详解

    2022-01-17 16:11:57
  • Android实现背景图滑动变大松开回弹效果

    2022-10-15 10:45:15
  • 利用Java读取二进制文件实例详解

    2023-07-27 03:25:42
  • 详解Spring Bean 之间的特殊关系

    2022-10-25 21:12:17
  • 浅析java移位符的具体使用

    2023-12-21 09:36:13
  • C# 大数据导出word的假死报错的处理方法

    2022-09-25 07:19:48
  • Kafka常用命令之kafka-console-consumer.sh解读

    2022-06-11 00:20:32
  • ubuntu用wifi连接android调试程序的步骤

    2021-08-05 16:40:27
  • Java实现选择排序

    2021-06-30 16:53:55
  • Android控件PopupWindow模仿ios底部弹窗

    2023-03-09 20:42:10
  • C#8.0新语法using declaration

    2023-10-23 00:57:54
  • 关于SpringBoot静态资源路径管理问题

    2022-12-04 03:51:29
  • asp之家 软件编程 m.aspxhome.com