简体   繁体   中英

Copying With Progress Bar not working

I kinda have a problem. I'm trying to make a form that copies stuff from point A to B with a statusbar. Now the copying works fine but the statusbar just isn't doing anything.. Anyone got any clue?

public partial class Form4A : Form
{
    public Form4A()
    {
        InitializeComponent();
        OtherSettings();
        BackgroundWorker.RunWorkerAsync(); // Starts wow copying
    }

    private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        string SourcePath = RegistryRead.ReadOriginalPath();
        string DestinationPath = RegistryRead.ReadNewPath();

        if (!Directory.Exists(SourcePath))
        {
            for (int i = 1; i <= 100; i++)
            {
                //Now Create all of the directories
                foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
                    SearchOption.AllDirectories))
                    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));

                //Copy all the files
                foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
                    SearchOption.AllDirectories))
                    File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));


                BackgroundWorker.ReportProgress(i);
            }
        }
    }
    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // Change the value of the ProgressBar to the BackgroundWorker progress.
        progressBar1.Value = e.ProgressPercentage;
        // Set the text.
        this.Text = e.ProgressPercentage.ToString();
    }

}

You say: if (!Directory.Exists(DestinationPath)) . This means that the loop will never be executed, if the desination path exists. Make sure you delete the DestinationPath before you test your code!

EDIT:

if (Directory.Exists(SourcePath)) {
    //Now Create all of the directories 
    string[] allDirectories = Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories);
    string[] allFiles = Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories);
    int numberOfItems = allDirectories.Length + allFiles.Length;
    int progress = 0;

    foreach (string dirPath in allDirectories) {
        Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
        progress++;
        BackgroundWorker.ReportProgress(100 * progress / numberOfItems);
    }

    //Copy all the files 
    foreach (string newPath in allFiles) {
        File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));
        progress++;
        BackgroundWorker.ReportProgress(100 * progress / numberOfItems);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM