多线程 断点续传

简介:

Stream iStream = null;
byte[] buffer = new Byte[10240];// 缓冲区块10K bytes :
int length;            
long dataToRead;           
string filepath = @"E:\software\SQL Server 2000 Personal Edition.ISO";
string filename = System.IO.Path.GetFileName(filepath);
try
{
    // 打开文件
    iStream = new FileStream(filepath, FileMode.Open,FileAccess.Read, FileShare.Read);
    Response.Clear();
    dataToRead = iStream.Length;
    long p = 0;
    if (Request.Headers["Range"] != null)
    {
        Response.StatusCode = 206;
        p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
    }
    if (p != 0)
    {
        Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
    }
    Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(Request.ContentEncoding.GetBytes(filename)));

    iStream.Position = p;
    dataToRead = dataToRead - p;              
    while (dataToRead > 0)
    {                  
        if (Response.IsClientConnected)
        {               
            length = iStream.Read(buffer, 0, 10240);                     
            Response.OutputStream.Write(buffer, 0, length);                      
            Response.Flush();

            buffer = new Byte[10240];
            dataToRead = dataToRead - length;
        }
        else
        {
            //如果用户断开连接 防止无限循环
            dataToRead = -1;
        }
    }
}
catch (Exception ex)
{             
    Response.Write("Error : " + ex.Message);
}
finally
{
    if (iStream != null)
    {
        iStream.Close();
    }
    Response.End();
}
}

 
 
,如需转载请自行联系原作者
相关文章
|
缓存 C# 图形学
C#多线程下载、断点续传的实现
做Unity热更功能的时候,发现单线程下载大尺寸资源文件的效率太低,专门去研究了下多线程下载,这里记录下相关知识点。
1047 0
|
算法 Android开发
Android--多线程断点续传
版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/chaoyu168/article/details/78057591 什么是多线程下载? 多线程下载其实就是迅雷,BT一些下载原理,通过多个线程同时和服务器连接,那么你就可以榨取到较高的带宽了,大致做法是将文件切割成N块,每块交给单独一个线程去下载,各自下载完成后将文件块组合成一个文件,程序上要完成做切割和组装的小算法。
1349 0