C# – Progress Bar help


I'm very much new to programming and have been doing fairly well so far. But progress bars still confuse me. The web unfortunately has to many differing examples for me to get anything out of them. Some say to use background worker some don't, etc. Below I have what I THINK should work but doesn't. Its just supposed to she a progress bar when copying file from one folder to another. Any help is appreciated.


        private void btnCopyFiles_Click(object sender, EventArgs e)
        string folder1 = @"c:\folder1\";
        string folder2 = @"c:\folder2\";

        DirectoryInfo di = new DirectoryInfo(folder1);
        FileInfo[] filelist = di.GetFiles("*.*");
        int count = di.GetFiles("*.*").Length;

        this.progressBar1 = new System.Windows.Forms.ProgressBar();
        progressBar1.Maximum = count;
        progressBar1.Minimum = 0;
        progressBar1.Step = 1;

        foreach (FileInfo file in filelist)
                this.Cursor = Cursors.WaitCursor;
                File.Copy(folder1 + @"\" + file.Name, folder2 + @"\" + file.Name, true);
                this.Cursor = Cursors.Default;
            catch (Exception error)
                MessageBox.Show("Error: " + error);

Best Solution

I'm assuming that you are using Visual Studio and have added the ProgressBar control by dragging it to the form. If this is correct, then following line, may be the problem:

this.progressBar1 = new System.Windows.Forms.ProgressBar();

By recreating the control, you are loosing its link to the form. Just remove or comment that line and try it again.