无法删除文件,因为它被另一个进程使用

时间:2012-05-12 15:21:26

标签: wpf multithreading file-io

我收到此异常

  

进程无法访问文件'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;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

下载真正取消时你需要等待。当调用_webClient.CancelAsync();下一个操作符在webClient取消之前执行immediatley。

可能需要在CancelAsync(...)

的回调中删除该文件
相关问题