下载文件

public void DownloadFile(string url, string savePath)
{
    long existingLength = 0;
    FileInfo fileInfo = new FileInfo(savePath);
    if (fileInfo.Exists)
        existingLength = fileInfo.Length;

    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
    request.AddRange((int)existingLength); // 设置Range值
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    using (Stream responseStream = response.GetResponseStream())
    {
        using (FileStream fs = new FileStream(savePath, FileMode.Append, FileAccess.Write))
        {
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                fs.Write(buffer, 0, bytesRead);
            }
        }
    }
}

 

 

posted on 2024-03-25 14:10  炼金师  阅读(27)  评论(0编辑  收藏  举报

导航