mpen
mpen

Reputation: 283293

Cannot delete file because it is used by another process

I'm getting this exception

The process cannot access the file 'myfile.zip' because it is being used by another process.

When I try to delete a file. I understand the error, but I'm not sure what other process could be using the file.

I'm downloading the file via WebClient asynchronously, but I cancel the download before trying to delete it, which means that process should relinquish it, no?

Here are the relevant methods. It's a simple file-downloader:

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;
        }
    }
}

Upvotes: 1

Views: 490

Answers (1)

gabba
gabba

Reputation: 2880

You need to wait when downloading realy canceled. When call _webClient.CancelAsync(); next operator executes immediatley before webClient canceled.

May be you need delete the file in callback of CancelAsync(...)

Upvotes: 1

Related Questions