Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Team,

I would like to insert the PROGRESS BAR while loading the file (with count) and while copying the images (with count).

WHILE LOADING THE FILE:

private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            //dlg.ShowDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                string fileName;
                fileName = dlg.FileName;
                using (StreamReader sr = new StreamReader(fileName))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        listBox1.Items.Add(line);
                        string[] findingparent = line.Split(',');
                        if (line.Contains(",Y,,") == true)
                        {
                            parents.Add(findingparent[0], ",Y,,," + findingparent[findingparent.Length - 1]);
                            parentcount++;
                        }
                        else
                        {
                            parents.Add(findingparent[0], ",,,,");
                            childcount++;
                        }
                            
                    }
                    sr.Close();
                    label6.Text = (listBox1.Items.Count).ToString();
                    label4.Text = parentcount.ToString();
                    label5.Text = childcount.ToString();
                }
            }
        }


WHILE COPYING THE IMAGES:

     if (!int.TryParse(textBox3.Text, out int thresholdValue) || thresholdValue < 1)
            {
                // TODO: Display an error message to the user
                return;
            }

            string source = textBox1.Text;
            string destination = textBox2.Text;
            int totalFileCount = 0;
            int currentSubFolder = 0;
            int remainingFileCount = 0;
            string destinationFolder = null;

            ISet<string> extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
    ".tif",
    ".tiff",
    ".jpg",
    ".jpeg"
};

            IEnumerable<string> files = Directory
                .EnumerateFiles(source, "*", SearchOption.AllDirectories)
                .Where(f => extensions.Contains(Path.GetExtension(f)));

            foreach (string sourceFile in files)
            {
                if (remainingFileCount == 0)
                {
                    // First file, or the sub-folder is full:
                    currentSubFolder++;
                    destinationFolder = Path.Combine(destination, currentSubFolder.ToString("D3"));
                    if (!Directory.Exists(destinationFolder)) Directory.CreateDirectory(destinationFolder);
                    remainingFileCount = thresholdValue;
                }

                string destinationFile = Path.Combine(destinationFolder, Path.GetFileName(sourceFile));
                File.Copy(sourceFile, destinationFile);
                totalFileCount++;
                remainingFileCount--;   
            }

            MessageBox.Show("All " + totalFileCount + " files are copied");


What I have tried:

I have tried adding a PROGRESS BAR in a Button click of COpy where files starts copying but i couldn't get the progress bar working on it

Tried the below code as well but not working:
pBar.Location = new System.Drawing.Point(20, 20);
          pBar.Width = 200;
          pBar.Height = 30;
          pBar.Name = "progressBar1";
          pBar.Dock = DockStyle.Bottom;
          pBar.Value = totalFileCount;
          this.Text = "Progress: " + totalFileCount.ToString() + "%";
Posted
Updated 15-Oct-20 20:12pm

Here, following guide should help: Set the Value Displayed by ProgressBar Control - Windows Forms .NET Framework | Microsoft Docs[^]

An example where progress bar increases by fixed value:
C#
public void loadFiles()  
{  
   // Sets the progress bar's minimum value to a number representing  
   // no operations complete -- in this case, no files read.  
   progressBar1.Minimum = 0;  
   // Sets the progress bar's maximum value to a number representing  
   // all operations complete -- in this case, all five files read.  
   progressBar1.Maximum = 5;  
   // Sets the Step property to amount to increase with each iteration.  
   // In this case, it will increase by one with every file read.  
   progressBar1.Step = 1;  

   // Uses a for loop to iterate through the operations to be  
   // completed. In this case, five files are to be copied into memory,  
   // so the loop will execute 5 times.  
   for (int i = 0; i <= 4; i++)  
   {  
      // Inserts code to copy a file  
      progressBar1.PerformStep();  
      // Updates the label to show that a file was read.  
      label1.Text = "# of Files Read = " + progressBar1.Value.ToString();  
   }  
}

An example where progress bar increases by dynamic value:
C#
public void readFiles()  
{  
   // Sets the progress bar's minimum value to a number
   // representing the hard disk space before the files are read in.  
   // You will most likely have to set this using a system call.  
   // NOTE: The code below is meant to be an example and
   // will not compile.  
   progressBar1.Minimum = AvailableDiskSpace();  
   // Sets the progress bar's maximum value to a number
   // representing the total hard disk space.  
   // You will most likely have to set this using a system call.  
   // NOTE: The code below is meant to be an example
   // and will not compile.  
   progressBar1.Maximum = TotalDiskSpace();  

   // Uses a for loop to iterate through the operations to be  
   // completed. In this case, five files are to be written  
   // to the disk, so it will execute the loop 5 times.  
   for (int i = 1; i<= 5; i++)  
   {  
      // Insert code to read a file into memory and update file size.  
      // Increases the progress bar's value based on the size of
      // the file currently being written.  
      progressBar1.Increment(FileSize);  
      // Updates the label to show available drive space.  
      label1.Text = "Current Disk Space Used = " + progressBar1.Value.ToString();  
   }  
}
 
Share this answer
 
The problem is that you are looping in your UI thread.

When you start an app, it has one thread - the UI thread - which handles all the display updates via Events. If your event handler - in this case button1_Click loops through the file adding lines to listboxes, copying files etc., and taking enough time that a progress bar is needed, then the single thread is busy for a significant time. Since it can only do one thing at a time, it cannot respond to Events which update screen controls until your handler has exited. So even a progress bar isn't a whole lot of use here as the thread which updates it on the users screen is busy copying files!

The solution is to move long running code into a second thread, freeing up the UI thread for display updates.
That can get complicated, because only the UI thread is allowed to access any Controls (including ListBox and ProgressBar controls) so you have to Invoke such code back onto the UI thread.

There is a solution that is pretty easy to use though: the BackgroundWorker Class (System.ComponentModel) | Microsoft Docs[^] allows you to report progress back to the UI thread which can update ListBoxes, progress bars, etc.

C#
private void FrmMain_Shown(object sender, EventArgs e)
    {
    BackgroundWorker work = new BackgroundWorker();
    work.WorkerReportsProgress = true;
    work.DoWork += Work_DoWork;
    work.ProgressChanged += Work_ProgressChanged;
    work.RunWorkerCompleted += Work_RunWorkerCompleted;
    work.RunWorkerAsync();
    }

private void Work_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
    // Do whatever is necessary after worker complete
    }

private void Work_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
    // Do display updates as files get copied
    }

private void Work_DoWork(object sender, DoWorkEventArgs e)
    {
    // Do the actual file copy and use ReportProgress to update the display.
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900