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

2024-04-29

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)。


您的代码表明您在新下载的文件上遇到了“正在使用的文件”异常。许多防病毒程序会自动扫描新创建和/或新下载的文件,并且可能会延迟关闭文件句柄,直到扫描完成。

如果这是您的问题,那么您无能为力按时关闭文件。您可以切换到在扫描期间不会锁定文件的其他防病毒软件,也可以在尝试使用最近关闭的文件时实施延迟+重试循环。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

File.Delete 进程无法访问该文件,因为该文件正在被另一个进程使用 的相关文章

随机推荐