How to Copy file with progress bar in C#

By FoxLearn 7/19/2024 2:13:09 AM   17.46K
Copying a file with a progress bar in a C# Windows Forms Application involves several steps, including setting up the UI components, handling the file copy operation, and updating the progress bar accordingly.

To implement file copy progress in C#, You can create a new windows forms project, then add label, button and progress bar control from the visual studio toolbox to your winform.

Next, You can design a simple UI that allows you to copy a file from the source to the destination directory, and show percentage complete in label, progress bar as shown below.

copy file with progress bar in c#

To copy file in c#, you can create an extension method as the following code.

//c# file copy progress
public static class FileInfoExtension
{
    public static void CopyTo(this FileInfo file, FileInfo destination, Action<int> progressCallback)
    {
        const int bufferSize = 1024 * 1024;
        byte[] buffer = new byte[bufferSize], buffer2 = new byte[bufferSize];
        bool swap = false;
        int progress = 0, reportedProgress = 0, read = 0;
        long len = file.Length;
        float flen = len;
        Task writer = null;
        using (var source = file.OpenRead())
        using (var dest = destination.OpenWrite())
        {
            dest.SetLength(source.Length);
            for (long size = 0; size < len; size += read)
            {
                if ((progress = ((int)((size / flen) * 100))) != reportedProgress)
                    progressCallback(reportedProgress = progress);
                read = source.Read(swap ? buffer : buffer2, 0, bufferSize);
                writer?.Wait();
                writer = dest.WriteAsync(swap ? buffer : buffer2, 0, read);
                swap = !swap;
            }
            writer?.Wait();
        }
    }
}

Finally, Add code to handle button click event in c# for the copy button as shown below.

private void btnCopy_Click(object sender, EventArgs e)
{
    var _source = new FileInfo(txtSource.Text);
    var _destination = new FileInfo(txtDestination.Text);
    //Check if the file exists, we will delete it
    if (_destination.Exists)
        _destination.Delete();
    //Create a tast to run copy file
    Task.Run(() =>
    {
        _source.CopyTo(_destination, x => progressBar.BeginInvoke(new Action(() => { progressBar.Value = x; lblPercent.Text = x.ToString() + "%"; })));
    }).GetAwaiter().OnCompleted(() => progressBar.BeginInvoke(new Action(() => { progressBar.Value = 100; lblPercent.Text = "100%"; MessageBox.Show("You have successfully copied the file !", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); })));
}

As you can see, we have created the CopyTo extension method of FileInfo class, so you can call it directly from the FileInfo class.

You can also add a browse button to the source textbox and the destination textbox that allows you to open the dialog box, then select the file you want to copy, and make sure the file is copied into the same folder as your application.