Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建下载加速器_C#_Winforms - Fatal编程技术网

C# 创建下载加速器

C# 创建下载加速器,c#,winforms,C#,Winforms,我指的是理解使用C#下载文件 代码使用传统方法读取流式 ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0 如何将要下载的文件划分为多个段,以便并行下载单独的段并合并它们 using (WebClient wcDownload = new WebClient()) { try { // Create a request to the file we are downlo

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

代码使用传统方法读取流式

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

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

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


ps:感谢用户svick

FYI,使用
UpdateProgressCallback
看起来这是WinForms代码。@JohnSaunders:这与问题一致。@Dan-o:但它与“asp.net”标记不一致。这就是问题所在。@johnsaunds:不知道我怎么会错过这个。我扫描了winforms的标签,没有看到它,只是错过了aspnet标签。愚蠢。如果您有一个NIC,多个连接可能会有什么改进?跟踪数据块是一回事,这样就可以重新开始下载,但通过单个管道执行多个操作通常不会提高性能。