110,534
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 下载文件
/// </summary>
/// <param name="url">文件路径</param>
/// <param name="startPos">起始位置</param>
/// <param name="bytesCount">读取字节数</param>
/// <returns></returns>
public byte[] DownLoadFile(string url, int startPos, int bytesCount)
{
ServicePointManager.DefaultConnectionLimit = 100;
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
request.KeepAlive = false;
request.AddRange(startPos, startPos + bytesCount - 1);
System.Net.WebResponse response =null ;
try
{
Console.WriteLine("请求数据");
response = request.GetResponse();
}
catch (WebException wex)
{
Console.WriteLine("请求数据WebException");
request.Abort();
throw wex;
}
catch (Exception ex)
{
Console.WriteLine("请求数据Exception");
request.Abort();
throw ex;
}
try
{
System.IO.Stream receiveStream = response.GetResponseStream();
System.IO.BinaryReader readStream = new System.IO.BinaryReader(receiveStream);
byte[] buffer = new byte[0];
byte[] read = new byte[256];
int count = readStream.Read(read, 0, 256);
while (count > 0)
{
Array.Resize<byte>(ref buffer, buffer.Length + count);
Array.Copy(read, 0, buffer, buffer.Length - count, count);
count = readStream.Read(read, 0, 256);
}
readStream.Close();
return buffer;
}
finally
{
response.Close();
}
}
}
byte[] buffer = null;
//当服务器返回的数据长度不等于文件长度时,下载完成
while (startPos < FileSize)
{
string errorInfo = null;
try
{
buffer = HttpDownload.DownLoadFile(url, (int)startPos, blockSize);
returnSize = buffer.Length;
startPos += returnSize;
WriteToFile(buffer);
Percent = (int)Math.Floor(startPos * 100.0 / FileSize);
}
catch (WebException wex)
{
errorInfo = "连接失败";
Thread.Sleep(3000);
}
catch (Exception ex)
{
errorInfo = "连接失败";
Thread.Sleep(3000);
}
}