删除通过 c# 中的后台工作程序创建的文件?

Delete a file that was created via background worker in c#?

我正在尝试删除通过后台工作程序创建的文件。我正在开发一个文件拆分程序,它将把一个大文本文件拆分成多个文本文件。我用一个cancel worker来停止后台worker。

进程遇到错误,因为文件当前被另一个进程(拆分进程)锁定,因此无法删除它。

调用cancel async时,有没有办法解除对它的锁定?

分割文件代码

 if (includeHeaders == "True")
        {
            using (var reader = new StreamReader(File.OpenRead(filepath)))
            {
                lines.Clear();
                _header = reader.ReadLine();
                lines.Add(_header);

                for (int i = 0; i < _lineCount; i++)
                {
                    if (bg.CancellationPending)
                    {
                        e.Cancel = true;
                        break;
                    }

                    int percentage = (i + 1) * 100 / _lineCount;

                    bg.ReportProgress(percentage);

                    lines.Add(reader.ReadLine());

                    if (i % numberOfRows == 0)
                    {
                        _counter++;


                        if (i == 0)
                        {
                            //skip first iteration 
                            _counter = 0;
                            continue;

                        }
                        _output = _tempath + "\" + "split\" + _fileNoExt + "_split-" + _counter + _fileExt;
                        File.WriteAllLines(_output, lines.ConvertAll(Convert.ToString));
                        lines.Clear();
                        lines.Add(_header);
                        Debug.WriteLine(_output);
                    }
                }
            }
        }

停止拆分的代码

private void StopSplit()
    {
        bg.CancelAsync();
        File.Delete(_output);
        ((MainWindow)Application.Current.MainWindow).DisplayAlert(
            "Split has been cancelled");
        ProgressBar.Value = 0;
    }

我知道代码不会删除所有创建的文件,我只是想先让删除工作起作用,然后再弄清楚其余的。

您假设 BackgroundWorker.CancelAsync 会立即取消您的操作,从而让您可以访问后台代码正在执行的资源。相反,它所做的只是设置您的 DoWork 事件处理程序当前正在检查的标志 (bg.CancellationPending)。

将 CancelAsync 之后的所有代码移动到另一个处理 RunWorkerCompleted 事件的事件处理程序中。

bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){
    if(e.Cancelled) {
        File.Delete(_output);
        ((MainWindow)Application.Current.MainWindow).DisplayAlert("Split has been cancelled");
        ProgressBar.Value = 0;
    }
    // TODO: handle your other, non-cancel scenarios
}