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

时间:2014-11-12 18:15:47

标签: c# file asynchronous webclient delete-file

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 个答案:

答案 0 :(得分:1)

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

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