
本文实例讲述了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,"项目管理工具.msi");
httpDownLoadHelper.Responsefile(httpContext.ApplicationInstance.Context.Request,httpContext.ApplicationInstance.Context.Response,102400);
希望本文所述对大家的C#程序设计有所帮助。
总结以上是内存溢出为你收集整理的C#中使用HttpDownLoadHelper下载文件实例全部内容,希望文章能够帮你解决C#中使用HttpDownLoadHelper下载文件实例所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)