C# Progress Bar in synchronous with process in real time

  • 4.1K Views
  • Last Post 31 August 2018
Ashraf Esmail posted this 30 August 2018

Using c# winforms project, How to make progress bar which its progress increases with a copying process (for many files) for instance in real time with label indicating the file which is already being copied (like the windows copier)

  • Liked by
  • Matevsz
lucy posted this 31 August 2018

We will use a BackgroudWorker to run async copy file

You can practice by creating a simple UI that allows you to copy the file as shown below

async copy file in c#

then add code to handle the copy button click event

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

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

        private string _source;
        private string _target;
        BackgroundWorker _worker;

        private void button1_Click(object sender, EventArgs e)
        {
            _target = Application.StartupPath;//Default path is Debug directory
            OpenFileDialog ofd = new OpenFileDialog() { Filter = "All|*.*" };
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                FileInfo fi = new FileInfo(ofd.FileName);//Get file name
                _target = _target + "\\" + fi.Name;//target file name copy
                _source = ofd.FileName;
                _worker.RunWorkerAsync();
            }
        }

        private void DoWork(object sender, DoWorkEventArgs e)
        {
            int bufferSize = 1024 * 512;
            using (FileStream source = new FileStream(_source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (FileStream target = new FileStream(_target, FileMode.Create, FileAccess.Write))
                {
                    //Read byte from source file, then write to target directory
                    int bytesRead = -1;
                    var totalReads = 0;
                    var totalBytes = source.Length;
                    byte[] bytes = new byte[bufferSize];
                    int prevPercent = 0;
                    while ((bytesRead = source.Read(bytes, 0, bufferSize)) > 0)
                    {
                        target.Write(bytes, 0, bytesRead);
                        totalReads += bytesRead;
                        int percent = System.Convert.ToInt32(((decimal)totalReads / (decimal)totalBytes) * 100);
                        if (percent != prevPercent)
                        {
                            _worker.ReportProgress(percent, percent);
                            prevPercent = percent;
                        }
                    }
                }
            }
        }

        private void ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
        {
            //update percentage to progressbar & label control
            progressBar1.Value = e.ProgressPercentage;
            label1.Text = $"{e.UserState}%";
            progressBar1.Update();
            label1.Update();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //init backgroudworker
            _worker = new BackgroundWorker();
            _worker.WorkerSupportsCancellation = false;
            _worker.WorkerReportsProgress = true;
            _worker.DoWork += DoWork;
            _worker.ProgressChanged += ProgressChanged;
            _worker.RunWorkerCompleted += RunWorkerCompleted;
        }

        private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("Copied");
        }
    }
}

First we will get the source file, then write your source file to the target directory

As you know, the BackgroudWorker supports delegate to handle your process

  • ProgressChanged event delegate to update percentage to your progressbar and label
  • DoWork event delegate to process copy file
  • RunWorkerCompleted to process complete copy file

To copy multiple files you should get a list of file that you want to copy, then use loop to process copy file

I hope you can solve the problem async copy file in c#

Close