WebClient 下载后正在使用的文件
File in Use after WebClient download
我已经下载了一个文件,并尝试根据其大小删除它,但是,它说该文件正在使用中。
WebClient wc = new WebClient();
wc.DownloadFileAsync(new Uri(sb.ToString()), sbFileLocation.ToString());
if (new FileInfo(sbFileLocation.ToString()).Length == 0)
{
File.Delete(sbFileLocation.ToString());
}
如您所见,File.Delete 引发异常,说明该文件正在使用中。
有什么方法可以关闭然后删除吗?
DownloadFileAsync(Uri, String, Object)
Downloads, to a local file, the resource with the specified URI. This
method does not block the calling thread.
这意味着文件可能(或可能不会)在您调用 File.Delete(sbFileLocation.ToString());
之前完全下载。这是典型的竞争条件,可以充分解释您的错误。
This method downloads the resource at the URI specified by in the
address parameter. When the download completes successfully, the
downloaded file is named fileName on the local computer. 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
event, the synchronous WebClient.DownloadFile
method or await
the Task based WebClient.DownloadFileTaskAsync
方法
我已经下载了一个文件,并尝试根据其大小删除它,但是,它说该文件正在使用中。
WebClient wc = new WebClient();
wc.DownloadFileAsync(new Uri(sb.ToString()), sbFileLocation.ToString());
if (new FileInfo(sbFileLocation.ToString()).Length == 0)
{
File.Delete(sbFileLocation.ToString());
}
如您所见,File.Delete 引发异常,说明该文件正在使用中。
有什么方法可以关闭然后删除吗?
DownloadFileAsync(Uri, String, Object)
Downloads, to a local file, the resource with the specified URI. This method does not block the calling thread.
这意味着文件可能(或可能不会)在您调用 File.Delete(sbFileLocation.ToString());
之前完全下载。这是典型的竞争条件,可以充分解释您的错误。
This method downloads the resource at the URI specified by in the address parameter. When the download completes successfully, the downloaded file is named fileName on the local computer. 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
event, the synchronous WebClient.DownloadFile
method or await
the Task based WebClient.DownloadFileTaskAsync
方法