[英]File in Use after WebClient download
I've downloaded a file and tried to delete it based on its size after doing so, however, it says the file is in use. 我已经下载了一个文件,并尝试根据其大小将其删除,但是,它表示该文件正在使用中。
WebClient wc = new WebClient();
wc.DownloadFileAsync(new Uri(sb.ToString()), sbFileLocation.ToString());
if (new FileInfo(sbFileLocation.ToString()).Length == 0)
{
File.Delete(sbFileLocation.ToString());
}
As you can see, File.Delete raises an exception, stating that the file is in use. 如您所见,File.Delete引发异常,表明该文件正在使用中。
Is there some way to close it and then delete it? 有什么办法可以关闭它,然后再删除它?
DownloadFileAsync(Uri, String, Object) DownloadFileAsync(Uri,String,Object)
Downloads, to a local file, the resource with the specified URI.
将具有指定URI的资源下载到本地文件。 This method does not block the calling thread.
此方法不会阻塞调用线程。
What this means is the file may (or may not) be completely downloaded before you call File.Delete(sbFileLocation.ToString());
这意味着在调用
File.Delete(sbFileLocation.ToString());
之前,可能会(或可能不会)完全下载文件File.Delete(sbFileLocation.ToString());
. 。 This is a typical race condition and fully explains your error.
这是典型的比赛情况,完全可以解释您的错误。
This method downloads the resource at the URI specified by in the address parameter.
此方法以address参数中指定的URI下载资源。 When the download completes successfully, the downloaded file is named fileName on the local computer.
下载成功完成后,下载的文件在本地计算机上名为fileName。 The file is downloaded asynchronously using thread resources that are automatically allocated from the thread pool.
使用从线程池自动分配的线程资源异步下载文件。 To receive notification when the file is available, add an event handler to the DownloadFileCompleted event.
要在文件可用时接收通知,请将事件处理程序添加到DownloadFileCompleted事件。
You either need to use the DownloadFileCompleted
event, the synchronous WebClient.DownloadFile
method or await
the Task based WebClient.DownloadFileTaskAsync
method 您或者需要使用
DownloadFileCompleted
事件,同步的WebClient.DownloadFile
方法,或者await
基于任务的WebClient.DownloadFileTaskAsync
方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.