Search code examples
c#.netrecursionbackgroundworker

Backgroundworker with recursive DirectorCopy function


I spent almost three days with this below, so I finally ended up here.

I have a function (from MSDN) which copies a folder with it's every file and subfolder. First it copies the main folder's files, then calls itself on each subfolder.

Here it is:

private void DirectoryCopy(string sourceDirName, string destDirName)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);
        DirectoryInfo[] dirs = dir.GetDirectories();

        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }

        // If the destination directory doesn't exist, create it. 
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }

        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string temppath = System.IO.Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, false);
        }

        // Copying subdirectories and their contents to new location. 
        foreach (DirectoryInfo subdir in dirs)
        {
            string temppath = System.IO.Path.Combine(destDirName, subdir.Name);
            DirectoryCopy(subdir.FullName, temppath, copySubDirs);
        }
    }

The problem is that it could take a long time therefore I tried to use BackgroundWorker, but I don't know how to place it in it's DoWork event.

If I place the first DirectoryCopy call in the DoWork event, can't handle the Cancel event:

private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        if (worker.CancellationPending)
        {
            e.Cancel = true;
            return;
        }
        DirectoryCopy(sourcePath, destPath, true);
    }

sourcePath and destPath are members of my class.

Any tips how can I handle the worker's Cancel event in the DirectoryCopy? Or any other tips to make it working?

Thanks!


Solution

  • Although I haven't worked with BackgroundWorker yet, looking at your question - a quick ( might be ill-logical ) suggestion would be to pass DoWorkEventArgs e inside the DirectoryCopy method like

    DirectoryCopy (sourcePath, destPath, true, worker , e)

    where BackgroundWoker worker , DoWorkEventArgs e and handle it whatever way you want it inside.

    Example :

    if (worker.CancellationPending)
         {
            // your code
            e.Cancel = true;
         }
    

    Hope this helps!