C#下载大文件并实现断点续传
转自
http://5543541.qzone.qq.com/blog/23
System.IO.Stream iStream = null;
byte[] buffer = new Byte[10240];
int length;
long dataToRead;
string filepath = "文件存放地址";
string filename = System.IO.Path.GetFileName(filepath);
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read,System.IO.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("真实文件名"));
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;
}
}
iStream.Close();
Response.End();
byte[] buffer = new Byte[10240];
int length;
long dataToRead;
string filepath = "文件存放地址";
string filename = System.IO.Path.GetFileName(filepath);
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read,System.IO.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("真实文件名"));
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;
}
}
iStream.Close();
Response.End();