c# - 创建下载加速器

标签 c# winforms

我指的是 this article了解使用 C# 进行文件下载。

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

((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0

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

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 });
        }
    }

最佳答案

你需要多个线程来完成它。 首先你启动第一个下载线程,创建一个网络客户端并获取文件大小。然后你可以启动几个新线程,其中添加一个下载范围标题。 您需要一种逻辑来处理下载的部分,并在下载完成后创建新的下载部分。

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

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

ps:感谢用户svick

关于c# - 创建下载加速器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499157/

相关文章:

c# - MemoryStream 没有向文件写入任何内容

c# - Viewinjection 统一失败

c# - 我如何在我的 ASP.NET 应用程序中为我的 ListView 使用 ItemCommand 事件

c# - 具有长json字符串参数的Wcf post方法

c# - 在设计器中打开自定义用户控件时,Visual Studio Professional 15.9.2 崩溃

c# - .NET/Windows 窗体 : remember windows size and location

c# - foreach 和集合的使用速度慢吗?

c# - ASP.NET MVC : Validation messages set in TryUpdateModel not showning ValidationSummary

c++ - opencl 内核文件未完全加载

c# - 如何构建 C# WinForms Model-View-Presenter(被动 View )程序?