输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小

本文介绍了一个使用C#实现的大文件下载方法,支持断点续传、速度限制等功能,适用于Web应用程序中的文件下载需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C# code
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->
///<summary>
/// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小
/// </summary>
/// <param name="MyRequest">Page.Request对象</param>
/// <param name="MyResponse">Page.Response对象</param>
/// <param name="MyFileName">下载文件名</param>
/// <param name="MyFullPath">带文件名下载路径</param>
/// <param name="MySpeed">每秒允许下载的字节数</param>
/// <returns>True Or False</returns>
public static bool DownLoadFile(HttpRequest MyRequest, HttpResponse MyResponse, string MyFileName, string MyFullPath, long MySpeed)
{
try
{
FileStream myFile
= new FileStream(MyFullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br
= new BinaryReader(myFile);

try
{
MyResponse.AddHeader(
"Accept-Ranges", "bytes");
MyResponse.Buffer
= false;

long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor(1000.0 * pack / MySpeed) + 1;

if (MyRequest.Headers["Range"] != null)
{
MyResponse.StatusCode
= 206;
string[] range = MyRequest.Headers["Range"].Split(new char[] { '=', '-' });
startBytes
= Convert.ToInt64(range[1]);
}

MyResponse.AddHeader(
"Content-Length", (fileLength - startBytes).ToString());

if ((startBytes != 0))
{
MyResponse.AddHeader(
"Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}

MyResponse.AddHeader(
"Connection", "Keep-Alive");
MyResponse.ContentType
= "application/octet-stream";
MyResponse.AddHeader(
"Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(MyFileName, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);

int maxCount = (int)Math.Floor(1.0 * (fileLength - startBytes) / pack) + 1;

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值