首页 文章

File.Delete进程无法访问该文件,因为它正被另一个进程使用

提问于
浏览
0
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) .

1 回答

  • 1

    您的代码建议您在新下载的文件上获取“正在使用的文件”例外 . 许多防病毒程序会自动扫描新创建的和/或新下载的文件,并可能会延迟关闭文件句柄,直到扫描完成 .

    如果这是你的问题,那么你就可以按时关闭文件了 . 您可以切换到不会在扫描期间保持文件锁定的其他防病毒,也可以在尝试使用最近关闭的文件时实施延迟重试循环 .

相关问题