【问题标题】:Cannot delete file because it is used by another process无法删除文件,因为它被另一个进程使用
【发布时间】:2012-05-12 23:25:22
【问题描述】:

我遇到了这个异常

该进程无法访问文件“myfile.zip”,因为它正被另一个进程使用。

当我尝试删除文件时。我了解该错误,但我不确定其他进程可能正在使用该文件。

我正在通过WebClient异步下载文件,但我在尝试删除它之前取消了下载,这意味着进程应该放弃它,不是吗?

以下是相关方法。这是一个简单的文件下载器:

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    string downloadFile = textBox1.Text.Trim();
    if (e.Key == Key.Return && downloadFile != "")
    {
        var dlg = new SaveFileDialog();
        dlg.FileName = Path.GetFileName(downloadFile);
        dlg.DefaultExt = Path.GetExtension(downloadFile);
        var result = dlg.ShowDialog();
        if(result.Value)
        {
            textBox1.Text = "";
            textBox1.Focus();
            _saveFile = dlg.FileName;
            progressBar1.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => progressBar1.Foreground = new SolidColorBrush(Color.FromRgb(0, 255, 0))));
            _webClient.DownloadFileAsync(new Uri(downloadFile), _saveFile);
        }
    }
}


private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    if (_webClient.IsBusy && _saveFile != null)
    {
        var result = MessageBox.Show("Download in progress. Are you sure you want to exit?", "Exit?", MessageBoxButton.YesNo, MessageBoxImage.Warning);
        if (result == MessageBoxResult.Yes)
        {
            _webClient.CancelAsync();
            File.Delete(_saveFile);
        }
        else
        {
            e.Cancel = true;
        }
    }
}

【问题讨论】:

    标签: wpf multithreading file-io


    【解决方案1】:

    下载真正取消时需要等待。当调用 _webClient.CancelAsync(); next 运算符在 webClient 取消之前立即执行。

    可能你需要在 CancelAsync(...) 的回调中删除文件

    【讨论】:

    • 那么我怎么知道它什么时候完成取消呢?我没有看到“DownloadCancelled”的事件。我认为CancelAsync 是同步的。 编辑: 没关系。阅读the remarks 解释它。
    猜你喜欢
    • 2012-08-04
    • 2014-05-26
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多