Use ProgressBar to copy folders and their contents

0

I have an application in C # WinForms that when clicking a button, should start copying various folders and their contents.

Since this process is time-consuming, I'd like the user to know how the progress of the process goes through ProgressBar .

I have already found some examples on the internet that exemplify a time-consuming process using a% re_de%, but I can not apply this type of example to my project.

What's the best way to do it? Get the number of folders and implement Thread.Sleep(10) as the folders are being copied?

How to do this?

    
asked by anonymous 23.03.2017 / 19:02

2 answers

2

You have to use a thread for this to work.

For each directory copied within the loop, run this command:

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

It would look something like this:

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

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

    contador++;
}
    
23.03.2017 / 19:19
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;
}
    
27.03.2017 / 02:45