Use Progressbar to copy folders and their contents

Asked

Viewed 179 times

0

I have an application in C# Winforms that when you click on a button, you should start copying several folders and their respective contents.

As this process is time consuming, I would like the user to know how the process is going through a ProgressBar.

I have already found some examples on the internet that exemplify a time-consuming process using a repetition of Thread.Sleep(10), but I can’t apply this kind of example to my project.

What is the best way to do it? Take the number of folders and implement the ProgressBar as folders are being copied?

How to do this?

2 answers

2

You have to use a thread to make it work.

Every directory copied within the loop, run this command:

BeginInvoke((MethodInvoker)delegate
{
    progressBar.Value = ((100 * contador) / diretorios.Count).ToString();
});

Would something like this:

int contador = 0;
foreach (var diretorio in diretorios)
{
    CopiarDiretorio();

    BeginInvoke((MethodInvoker)delegate
    {
        progressBar.Value = ((100 * contador) / diretorios.Count).ToString();
    });

    contador++;
}
  • 1

    Thank you very much @Heverson! Helped me a lot :)

  • 1

    Accept the reply @Cristianquadros

  • Falou @Cristianquadros!

1

One option is to use BackgroundWorker.

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){
...
    foreach (FileInfo f in files)
    {
       f.CopyTo(destino);
       progresso++;
       backgroundWorker1.ReportProgress(progresso * 100 / files.Lenght);
    }
....
}


private void backgroundWorkerTransmitir_ProgressChanged(object sender, ProgressChangedEventArgs e){
    progressBar1.Value = e.ProgressPercentage;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.