【发布时间】:2012-09-21 03:07:49
【问题描述】:
我指的是 this article 了解使用 C# 进行文件下载。
代码使用传统的方式读取 Stream like
((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0
如何将一个要下载的文件分割成多个segment,以便并行下载单独的segment并合并它们?
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 });
}
}
【问题讨论】:
-
仅供参考,使用
UpdateProgressCallback看起来这是 WinForms 代码。 -
@JohnSaunders:这与问题一致。
-
@Dan-o: 但它与“asp.net”标签不一致。因此问题。
-
@JohnSaunders:不知道我是怎么错过的。我扫描了 winforms 的标签,没有看到它,只是错过了 aspnet 标签。愚蠢。
-
如果你有一个网卡,多个连接可能会带来什么改进?跟踪数据块以便重新开始下载是一回事,但通过单个管道执行多个操作通常不会提高性能。