每个按钮单击都会增加后台工作人员运行以复制文件的次数

Each button click incriments the times the background worker runs to copy files

我有一个 windows 应用程序 (C#),我在其中将一些文件从目录(递归)复制到用户从 UI.

中选择的驱动器

效果很好 - 所有文件都移动到适当的驱动器。

但是这个过程随着按钮被点击的次数增加而增加。

I.E.

我无法找到在我的以下代码中调用它以增加过程完成次数的位置。

我确定我在某处遗漏了它 - 我只是不知道在哪里。

我正在使用进度条,这样我可以让用户以图形方式了解正在发生的事情 - 它按预期运行。

/*
 * ***** *
 * Copy all directories and files recursively
 * ***** *
*/
public void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
{
    foreach (DirectoryInfo dir in source.GetDirectories())
    {
        if ((dir.Name == "My Music") || (dir.Name == "My Pictures") || (dir.Name == "My Videos"))
        {
            //do nothing with it since it is just a system link we cannot access
        }
        else
        {
            CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
        }
    }
    foreach (FileInfo file in source.GetFiles())
        file.CopyTo(Path.Combine(target.FullName, file.Name), true);
}

/* 
 * *****
 * PROGRESS BAR METHODS *
 * *****
*/
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string buttonSender = clickedButton; //Desktop, Documents, etc.
    switch (buttonSender) {
        case "Desktop":
            destinationLocation = selectedDrive + "Backups-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + "\Desktop\";
            string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            source = new DirectoryInfo(desktopFolder);
            break;
        case "Documents":
            destinationLocation = selectedDrive + "Backups-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + "\Documents\";
            string documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            source = new DirectoryInfo(documentsFolder);
            break;
        case "Favorites":
            destinationLocation = selectedDrive + "Backups-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + "\Favorites\";
            string favoritesFolder = Environment.GetFolderPath(Environment.SpecialFolder.Favorites);
            source = new DirectoryInfo(favoritesFolder);
            break;
        default :

            break;
    }

    DirectoryInfo target = new DirectoryInfo(destinationLocation);
    fileCount = source.GetFiles("*", SearchOption.AllDirectories).Length;
    totalFileCount = fileCount;
    int total = totalFileCount; //some number (this is your variable to change)!!
    for (int i = 0; i <= total; i++) //some number (total)
    {
        System.Threading.Thread.Sleep(100);
        int percents = (i * 100) / total;
        bgWorker.ReportProgress(percents, i);
        //2 arguments:
        //1. procenteges (from 0 t0 100) - i do a calcumation 
        //2. some current value!
    }
    if (!Directory.Exists(destinationLocation))
    {
        Directory.CreateDirectory(destinationLocation);
    }
    CopyFilesRecursively(source, target);
}

void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    essentialItemsProgressBar.Visible = true;
    essentialItemsProgressBar.Value = e.ProgressPercentage;

    int percent = (int)(((double)(essentialItemsProgressBar.Value - essentialItemsProgressBar.Minimum) /
    (double)(essentialItemsProgressBar.Maximum - essentialItemsProgressBar.Minimum)) * 100);
    using (Graphics gr = essentialItemsProgressBar.CreateGraphics())
    {
        gr.DrawString(percent.ToString() + "%",
            SystemFonts.DefaultFont,
            Brushes.Black,
            new PointF(essentialItemsProgressBar.Width / 2 - (gr.MeasureString(percent.ToString() + "%",
                SystemFonts.DefaultFont).Width / 2.0F),
            essentialItemsProgressBar.Height / 2 - (gr.MeasureString(percent.ToString() + "%",
                SystemFonts.DefaultFont).Height / 2.0F)));
    }

    essentialItemsProgressLabel.Visible = true;
    essentialItemsProgressLabel.Text = String.Format("Progress: {0} % - All {1} Files Transferred", e.ProgressPercentage, clickedButton);
    //essentialItemsProgressLabel.Text = String.Format("Total items transfered: {0}", e.UserState);
}

void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //do the code when bgv completes its work
    essentialItemsProgressBar.Visible = false;
}
/* 
 * *****
 * END OF PROGRESS BAR METHODS *
 * *****
*/
/*
 * ***** DESKTOP BACKUP ***** *
*/
private void backupDesktopButton_Click(object sender, EventArgs e)
{
    clickedButton = ((Button)sender).Text.ToString();
    selectedDrive = backupDriveCombo.SelectedItem.ToString();
    bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
    bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
    bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
    bgWorker.WorkerReportsProgress = true;
    bgWorker.RunWorkerAsync();
}
/*
 * ***** DOCUMENTS BACKUP ***** *
*/
private void backupDocumentsButton_Click(object sender, EventArgs e)
{
    clickedButton = ((Button)sender).Text.ToString();
    selectedDrive = backupDriveCombo.SelectedItem.ToString();
    bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
    bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
    bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
    bgWorker.WorkerReportsProgress = true;
    bgWorker.RunWorkerAsync();
}

问题出在这一行(在backupDocumentsButton_Click()方法中):

bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);

您应该只执行一次(即在创建 bgWorker 时),但您在每次单击按钮时都执行此操作。第一次单击后,您向按钮添加一个处理程序,第二次单击后,您再添加一个 - 它将被调用 2 次...

您应该更改您的代码:

private void backupDocumentsButton_Click(object sender, EventArgs e)
{
    clickedButton = ((Button)sender).Text.ToString();
    selectedDrive = backupDriveCombo.SelectedItem.ToString();
    // without these lines
    // bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork); 
    // bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
    // bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
    bgWorker.WorkerReportsProgress = true;
    bgWorker.RunWorkerAsync();
}

并且你应该在创建 bgWorker 之后添加行,即:

BackgroundWorker bgWorker = new BackgroundWorker();
bgWorker.DoWork += bgWorker_DoWork;
bgWorker.ProgressChanged += bgWorker_ProgressChanged;
bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;

您应该只添加一次事件处理程序。