[英]File.Delete error “The process cannot access the file because it is being used by another process”
[英]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;
}
請幫忙! 有時我會得到一個例外:
File.Delete進程無法訪問文件,因為它正在被另一個進程使用
我不知道為什么(我處置了WebClient)。
您的代碼建議您在新下載的文件上遇到“正在使用文件”異常。 許多防病毒程序會自動掃描新創建和/或新下載的文件,並且可能會延遲關閉文件句柄,直到完成掃描為止。
如果這是您的問題,那么您將無法按時關閉文件。 您可以切換到另一種不會在掃描過程中將文件鎖定的防病毒軟件,也可以在嘗試使用最近關閉的文件時實施“延遲+重試”循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.