簡體   English   中英

具有遞歸DirectorCopy功能的Backgroundworker

[英]Backgroundworker with recursive DirectorCopy function

我在下面花了將近三天的時間,所以終於在這里結束了。

我有一個函數(來自MSDN),該函數將每個文件和子文件夾都復制到一個文件夾中。 首先,它復制主文件夾的文件,然后在每個子文件夾中調用自身。

這里是:

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

問題是它可能需要很長時間,因此我嘗試使用BackgroundWorker,但是我不知道如何將其放置在DoWork事件中。

如果我將第一個DirectoryCopy調用放置在DoWork事件中,則無法處理Cancel事件:

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

sourcePath和destPath是我的課程的成員。

有什么技巧可以處理DirectoryCopy中工作程序的Cancel事件? 或其他任何使它起作用的提示?

謝謝!

盡管我還沒有使用BackgroundWorker但是看着您的問題-一個快速的建議(可能不合邏輯)是在DirectoryCopy方法內部傳遞DoWorkEventArgs e ,例如

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

在這里,BackgroundWoker worker,DoWorkEventArgs e可以在您想要的任何內部對其進行處理。

范例:

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

希望這可以幫助!

最好和最簡單的方法是使用Directory.EnumerateDirectories(,,)

這樣可以從代碼中刪除遞歸,並使其更容易停止。

foreach(var dir in Directory.EnumerateDirectories(sourceDir, "*.*", SearchOption.AllDirectories)
{    
   foreach(var file in Directory.EnumerateDirectories(dir, "*.*")
   {
     if (worker.CancellationPending)
     {
        e.Cancel = true;
        return;
     }

     // copy file
   }      
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM