我正在尝试从FTP服务器下载文件并显示进度条。
文件正在下载,ProgressChanged事件被调用,但是在事件参数中TotalBytesToReceive总是-1。TotalBytes增加,但是没有总数我无法计算百分比。
我想我可以通过其他ftp命令找到文件大小,但我想知道为什么这种方法不起作用?
我的代码:
FTPClient request = new FTPClient();
request.Credentials = credentials;
request.DownloadProgressChanged += new DownloadProgressChangedEventHandler(request_DownloadProgressChanged);
//request.DownloadDataCompleted += new DownloadDataCompletedEventHandler(request_DownloadDataCompleted);
request.DownloadDataAsync(new Uri(folder + file));
while (request.IsBusy) ;
....
static void request_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
if (e.TotalBytesToReceive == -1)
{
l.reportProgress(-1, FormatBytes(e.BytesReceived) + " out of ?" );
}
else
{
l.reportProgress(e.ProgressPercentage, "Downloaded " + FormatBytes(e.BytesReceived) + " out of " + FormatBytes(e.TotalBytesToReceive) + " (" + e.ProgressPercentage + "%)");
}
}
....
class FTPClient : WebClient
{
protected override WebRequest GetWebRequest(System.Uri address)
{
FtpWebRequest req = (FtpWebRequest)base.GetWebRequest(address);
req.UsePassive = false;
return req;
}
}
感谢。
WebClient
实现来处理它。寻找有趣的属性/方法进行重写。 - leppieWebClient
,但似乎很难在没有大量 hack 的情况下实现。 - leppie