C# ProgressBar not working

Hi,
I am trying to develop a file/folders lister but when I try to deploy the progressBar component it is not working. I did it this way because I need to be able to capture when cancel button has been clicked.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace listaEstructura
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnListar_Click(object sender, EventArgs e)
        {

            try
            {
                GetFiles();
                ProgressBar();
            }
            catch (Exception ex)
            {

                this.richTextBox1.Text = ex.Message;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Start the BackgroundWorker.
            backgroundWorker1.RunWorkerAsync();
        }

        private bool clickedButton = false;

        private void GetFiles()
        {
            List<String> Myfiles = new List<string>();
            IEnumerable<string> allFiles = System.IO.Directory.EnumerateFiles(txtRuta.Text, "*.*", System.IO.SearchOption.AllDirectories);

            try
            {
                
                foreach (string filename in allFiles)
                {
                    this.richTextBox1.Text = string.Join(Environment.NewLine, allFiles);
                    ProgressBar();

                    if (clickedButton == true)
                    {
                        MessageBox.Show("boton de cancelar presionado");
                        break;
                    }
                }
            }

            catch (SystemException excpt)
            {
                this.richTextBox1.Text = excpt.Message;
            }
        }

        private void btnDir_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                txtRuta.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void btnCancelar_Click(object sender, EventArgs e)
        {
            clickedButton = true;
            if (backgroundWorker1.IsBusy)
            {
                backgroundWorker1.CancelAsync();
            }
        }

        private void ProgressBar()
        {
            lblPublish.Text = "Starting publication...";
            //DoWork
            

            if (backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            List<string> allAcros = new List<string>();
            foreach (var acro in allAcros)
            {
                backgroundWorker1.ReportProgress(allAcros.IndexOf(acro));
                if (backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true;
                    backgroundWorker1.ReportProgress(0, acro);
                    return;
                }
                Thread.Sleep(500);
            }

        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            List<string> acros = new List<string>();
            progressBar1.Value = e.ProgressPercentage;
            for (int i = 0; i < acros.Count; i++)
            {
                progressBar1.Value = e.ProgressPercentage;
                lblPublish.Text = string.Format("Processing {0}...", e.UserState);
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                lblPublish.Text = "Processing cancelled";
            }
            else if (e.Error != null)
            {
                lblPublish.Text = e.Error.Message;
            }
            else
            {
                progressBar1.Value = 100;
                lblPublish.Text = "Publish Complete";

            }
        }

    }
}

Open in new window

LVL 2
José PerezAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
May I be the first to say...what a mess.  Half the code in there doesn't actually do anything useful.  =\

You can't cancel it because System.IO.Directory.EnumerateFiles() is a blocking operation that can't be cancelled.  Once you start it you'll just have to wait until it is done.  With that in mind, you also can't get any progress from it.

Additionally, you're doing a recursive search right?...so what progress would you report if you could?  We don't have any idea how deep the file system goes or how many files it will return.  The only way you could know that information would be to perform the same search TWICE...which would be a waste of time.

For situations like these you could simply put a ProgressBar in "Marquee" mode, which simply animates forever to show the user that "something" is happening....

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
Last parting thought: Put the System.IO.Directory.EnumerateFiles() call in the DoWork() handler as that is what it's for.  =)
käµfm³d 👽Commented:
@Mike
You can't cancel it because System.IO.Directory.EnumerateFiles() is a blocking operation that can't be cancelled.
That is not correct. EnumerateFiles returns an enumerator, which can be iterated over. GetFiles, on the other hand, does block. This is why I suggested the OP switch from the latter to the former in his previous question.

From https://msdn.microsoft.com/en-us/library/dd383458(v=vs.110).aspx :
The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.
Exploring SharePoint 2016

Explore SharePoint 2016, the web-based, collaborative platform that integrates with Microsoft Office to provide intranets, secure document management, and collaboration so you can develop your online and offline capabilities.

Mike TomlinsonHigh School Computer Science, Computer Applications, and Mathematics TeachersCommented:
Fair enough käµfm³d   👽!

...and if he moves the call to a background thread then it can be cancelled as you said.

But I still don't see any way to report any meaningful progress.
käµfm³d 👽Commented:
Without first getting a count, I I agree.
AndyAinscowFreelance programmer / ConsultantCommented:
One could always do it the Microsoft way.
After 20 seconds - 50% done
After 40 seconds - 90% done
after 60 seconds - 99% done
after 20 minutes - 99.5% done
.....
José PerezAuthor Commented:
Any suggestion on how can I make it work?
käµfm³d 👽Commented:
Honestly, I don't believe so. As best I can tell, the only way to get a count of how many files are in a directory is to iterate over the directory. And it seems you observed that this was very slow. So regardless of which approach you take--EnumerateFiles vs GetFiles--you're going to incur some slowness. If the progress bar is important to you, then you're going to have to loop over the files to gather the count. Then you would loop over the files a 2nd time to actually process them (and update your progress bar).
José PerezAuthor Commented:
mmm that's bad :(
Any link where I can learn how to do an app like this and possible integrate a progressBar?
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.