[英]File.Delete the process cannot access the file because it is being used by another process
public bool DownloadMp3File (DownloadedMp3 mp3) {
WebClient client = new WebClient ();
string filePath = "";
bool wasDownload = false;
try {
string song = mp3.SongName;
filePath = @"mp3\" + song + ".mp3";
if (File.Exists (filePath)) {
File.Delete (filePath);
}
DateTime tryCountNow = DateTime.Now;
client = new WebClient ();
client.DownloadFileAsync (new Uri (mp3.Url), filePath);
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
DateTime start = DateTime.Now;
bool notDownload = false;
downloadComplete = false;
while (!downloadComplete) {
DateTime now = DateTime.Now;
TimeSpan ts = now - start;
int min = ts.Minutes;
int sec = ts.Seconds;
if (10 < sec && 0 == downloadProgress) {
notDownload = true;
client.CancelAsync ();
break;
}
if (min == 1) {
notDownload = true;
client.CancelAsync ();
break;
}
Thread.Sleep (30);
}
if (!notDownload) {
client.CancelAsync ();
client.OpenRead (mp3.Url);
int downloadedFileSize = Convert.ToInt32 (client.ResponseHeaders["Content-Length"]);
FileInfo localFile = new FileInfo (filePath);
if (localFile.Length == downloadedFileSize) {
wasDownload = true;
}
}
}
catch {
downloadProgress = 0;
downloadComplete = false;
}
finally {
client.CancelAsync ();
client.Dispose ();
downloadComplete = false;
downloadProgress = 0;
GC.Collect ();
if (!wasDownload) {
if (File.Exists (filePath)) {
FileSecurity fs = File.GetAccessControl (filePath);
File.Delete (filePath);
}
}
Application.Current.Dispatcher.BeginInvoke (
DispatcherPriority.Background,
new Action (() =>
MainWindow.label3.Content = ""
));
}
return wasDownload;
}
Please help! 请帮忙! I sometimes get that exception: 有时我会得到一个例外:
File.Delete the process cannot access the file because it is being used by another process File.Delete进程无法访问文件,因为它正在被另一个进程使用
I can't find out why (I disposed WebClient). 我不知道为什么(我处置了WebClient)。
Your code suggests you're getting the "file being used" exception on a file that was newly downloaded. 您的代码建议您在新下载的文件上遇到“正在使用文件”异常。 Many anti-virus programs automatically scan newly created and/or newly downloaded files, and may delay closing the file handle until the scan is done. 许多防病毒程序会自动扫描新创建和/或新下载的文件,并且可能会延迟关闭文件句柄,直到完成扫描为止。
If that is your problem, then there's nothing more you can to do close the file on time. 如果这是您的问题,那么您将无法按时关闭文件。 You can either switch to a different anti-virus that doesn't keep files locked during scans, or you can implement a delay+retry loop when trying to use a file that's recently been closed. 您可以切换到另一种不会在扫描过程中将文件锁定的防病毒软件,也可以在尝试使用最近关闭的文件时实施“延迟+重试”循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.