简体   繁体   中英

Progress bar in wpf c#

Can anyone help me how can I integrate a progress bar in one of my methods? What I mean is when I execute a method example to extract zip files I will show a progress bar to know the progress of my method and as the method is done, the progress bar will reach 100%.

Here is my code for extracting files where in I want to add a progress bar

public void ExtractFiles()
{
     foreach (var file in d.GetFiles("*."))
     {
          if (!Directory.Exists(targetPath))
              Directory.CreateDirectory(targetPath);

          if (!File.Exists(targetPath + file.Name))
          {
              Directory.Move(file.FullName, targetPath + file.Name);
          }
          else
          {
              File.Delete(targetPath + file.Name);
              Directory.Move(file.FullName, targetPath + file.Name);
          }
     }
}

I want to know how can I show the % of my progress bar depending in the progress of my method.

Since you have it in the same form it should be pretty straight forward..

Assuming the you have named you ProgressBar as pb, you could try something like this..

public void ExtractFiles()
{
     var total = d.GetFiles("*.").count();
     var progressChange =  100/total;

    foreach (var file in d.GetFiles("*."))
    {
        if (!Directory.Exists(targetPath))
            Directory.CreateDirectory(targetPath);

        if (!File.Exists(targetPath + file.Name))
        {
            Directory.Move(file.FullName, targetPath + file.Name);
        }
        else
        {
            File.Delete(targetPath + file.Name);
            Directory.Move(file.FullName, targetPath + file.Name);
        }
        pb.Value += progressChange;
    }
}

Copied the code from @bit and changed little bit.

Try this:

public void ExtractFiles()
{
     var files = d.GetFiles("*.");
     int total = files.Count();
     var progressChange = 100/total;

    foreach (var file in files)
    {
        if (!Directory.Exists(targetPath))
            Directory.CreateDirectory(targetPath);

        if (!File.Exists(targetPath + file.Name))
        {
            Directory.Move(file.FullName, targetPath + file.Name);
        }
        else
        {
            File.Delete(targetPath + file.Name);
            Directory.Move(file.FullName, targetPath + file.Name);
        }
        //Here is the little bit change I did.
        pb.Dispatcher.BeginInvoke(new Action(()=>{
            pb.Value += progressChange;
        }));

    }
}

I hope that helps.

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