0

我编写了一个帮助类来使用 webclient 类从服务器下载文件。代码一直运行良好,直到不久前。突然代码不起作用,下载进度始终为 0,要接收的总字节数始终为 -1。下载工作正常,但问题仅在于实际进度更改。从下载过程开始到结束,下载进度保持为零,即使要接收的总字节数也保持为 -1。

请找到下面提到的示例代码。

public class FileDownloader
    {
        private string _zipFilePath;
        private string _destinationPath;
        private int _productId;
        public Action<int,int> progressListener;
        private WebClient _client;
        public void Download(string cloudPath, string localPath,int id)
        {
            _productId = id;
            _zipFilePath = localPath +id+ ".zip";
            _destinationPath = localPath + id;
            if (!Directory.Exists(localPath))
            {
                Directory.CreateDirectory(localPath);
            }
            _client = new WebClient();
            if (cloudPath != "")
            {
                Uri uri = new Uri(cloudPath);
                _client.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallback);
                _client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
                _client.DownloadFileAsync(uri, _zipFilePath);   
            }else
            {
                progressListener?.Invoke(_productId, -1);
            }
        }

        public void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
        {
            if(e.ProgressPercentage != 100)
                progressListener?.Invoke(_productId, e.ProgressPercentage);
        }

        public void CancelDownload()
        {
            _client.CancelAsync();
        }

        public void DownloadFileCallback(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled == false && e.Error == null)
            {
                //UnzipContent(_destinationPath,_zipFilePath);
                UnzipHandler unzipHandler = new UnzipHandler(_destinationPath, _zipFilePath,new UnzipCompletionCallback(UnzippedCourse));
                Thread thread = new Thread(new ThreadStart(unzipHandler.UnzipContent));
                thread.Start();
            }
            else
            {
                DeleteZip(_zipFilePath);
                progressListener?.Invoke(_productId, -1);
            }
        }

        private void DeleteZip(string zipPath)
        {
            if (File.Exists(zipPath))
            {
                File.Delete(zipPath);
            }
        }

        public void UnzippedCourse(bool status)
        {
            DeleteZip(_zipFilePath);
            if(status)
                progressListener?.Invoke(_productId, 100);
            else
                progressListener?.Invoke(_productId, -1);
        }

        public delegate void UnzipCompletionCallback(bool result);
    } 
4

0 回答 0