Webclient返回下载进度为0

时间:2018-11-21 11:38:59

标签: xamarin xamarin.ios xamarin.android webclient webclient-download

我编写了一个帮助程序类,可以使用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);
    } 

0 个答案:

没有答案
相关问题