一聚教程网:一个值得你收藏的教程网站

热门教程

Asp.net(c#)实现多线程断点续传

时间:2022-06-25 04:59:47 编辑:袖梨 来源:一聚教程网

asp教程.net(c#)实现多线程断点续传

stream istream = null;
byte[] buffer = new byte[10240];// 缓冲区块10k bytes :
int length;           
long datatoread;          
string filepath = @"e:softwaresql 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();
}
}

热门栏目