Search code examples
c#backgroundworker

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


I'm trying to delete a file that is created via a background worker. I'm working on a file split program, it will go through and split a large text file into multiple text files. I use a cancel worker to stop the background worker.

The process runs into an error as the file is currently locked by another process(the split process) so it cannot delete it.

Is there a way to release the lock on it when the cancel async is called?

Split file Code

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

Code to stop split

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

I'm aware the code will not delete all the files made, i'm just trying to get the delete to work first before figuring out the rest.


Solution

  • You are assuming that BackgroundWorker.CancelAsync will immediately cancel your operation and thus give you access to resources your background code is executing. Instead, all it does is set the flag that your DoWork event handler is currently checking (bg.CancellationPending).

    Move all code after CancelAsync into another event handler that handles the RunWorkerCompleted event.

    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
    }