首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建下载加速器

创建下载加速器
EN

Stack Overflow用户
提问于 2012-09-19 23:10:16
回答 1查看 1.2K关注 0票数 3

我指的是理解使用C#下载文件的this article

代码使用传统方法读取Stream like

代码语言:javascript
复制
((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0

如何将要下载的文件分成多个段,以便可以并行下载多个段并合并它们?

代码语言:javascript
复制
using (WebClient wcDownload = new WebClient())
{
    try
    {
        // Create a request to the file we are downloading
        webRequest = (HttpWebRequest)WebRequest.Create(txtUrl.Text);
        // Set default authentication for retrieving the file
        webRequest.Credentials = CredentialCache.DefaultCredentials;
        // Retrieve the response from the server
        webResponse = (HttpWebResponse)webRequest.GetResponse();
        // Ask the server for the file size and store it
        Int64 fileSize = webResponse.ContentLength;

        // Open the URL for download 
        strResponse = wcDownload.OpenRead(txtUrl.Text);
        // Create a new file stream where we will be saving the data (local drive)
        strLocal = new FileStream(txtPath.Text, FileMode.Create, FileAccess.Write, FileShare.None);

        // It will store the current number of bytes we retrieved from the server
        int bytesSize = 0;
        // A buffer for storing and writing the data retrieved from the server
        byte[] downBuffer = new byte[2048];

        // Loop through the buffer until the buffer is empty
        while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
        {
            // Write the data from the buffer to the local hard drive
            strLocal.Write(downBuffer, 0, bytesSize);
            // Invoke the method that updates the form's label and progress bar
            this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize });
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-21 03:07:49

你需要几个线程来完成这个任务。首先,您启动第一个下载线程,创建一个you客户端并获取文件大小。然后,您可以启动几个新线程,这些线程添加一个下载范围头。您需要一个逻辑来处理下载的部分,并在一个下载部分完成时创建新的下载部分。

http://msdn.microsoft.com/de-de/library/system.net.httpwebrequest.addrange.aspx

我注意到WebClient实现有时有一个奇怪的行为,所以如果你真的想写一个“大”的下载程序,我仍然建议你实现一个自己的超文本传输协议客户端。

ps:感谢用户svick

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12499157

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档