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

本文关键字:工作程序 创建 文件 后台 删除 | 更新日期: 2023-09-27 18:28:14

我正试图删除一个通过后台工作程序创建的文件。我正在开发一个文件分割程序,它将把一个大的文本文件分割成多个文本文件。我使用取消辅助进程来停止后台辅助进程。

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

当调用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;
    }

我知道代码不会删除所有制作的文件,我只是想在弄清楚其他文件之前先删除。

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

您假设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
}