简体   繁体   English

WebClient.DownloadFileTaskAsync和File.Exists

[英]WebClient.DownloadFileTaskAsync and File.Exists

I'm using the following code to download a file and verify if the download succeeded: 我正在使用以下代码下载文件并验证下载是否成功:

        try
        {
            UpdateAvailable = false;
            Downloading = true;

            using (var webclient = new WebClient { CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore) })
            {
                var file = Path.Combine(basePath, filename);
                await webclient.DownloadFileTaskAsync(updaterexe_fileurl, Path.Combine(basePath, updaterexe_filename));
                await webclient.DownloadFileTaskAsync(updatefileurl, file);
            }

            if (!File.Exists(filename))
            {
                Error = "Error downloading update. Please try again.";
                Log.Error("Error downloading update. Please try again (file does not exist).");
            }
            else
            {
                DownloadReady = true;
            }
        }
        catch (Exception ex)
        {
            Log.Error("Error downloading update: " + ex);
            Error = ex.Message;
        }
        finally
        {
            Downloading = false;
        }

This works in most cases. 在大多数情况下,这是可行的。 But I got multiple reports from end-users that sometimes they get the 'try again' error message. 但是我从最终用户那里收到了多个报告,有时他们会收到“重试”错误消息。

How is this even possible? 这怎么可能? Clearly, WebClient didn't throw an exception, but it also failed to download the file (it did not exist on disk). 显然,WebClient不会引发异常,但是它也无法下载文件(磁盘上不存在该文件)。

Is this a caching issue? 这是一个缓存问题吗? Am I missing any other error handling? 我是否还缺少其他错误处理?

If it's a disk caching issue, I thought about adding the following: 如果这是磁盘缓存问题,我考虑添加以下内容:

            int count = 0;
            while (count < 3 || !File.Exists(filename))
            {
                Thread.Sleep(1000);
                count++;
            }

But this feels very hacky. 但这感觉很hacky。

Any ideas? 有任何想法吗?

You download to file , which is Path.Combine(basePath, filename) but you never check to see whether file exists, you check to see whether filename exists. 您下载到file Path.Combine(basePath, filename)但从未检查file是否存在,而是检查filename是否存在。

If basePath and the current working directory differ, the file "won't exist". 如果basePath和当前工作目录不同,则文件“不存在”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM