How to make a file copy progress in C#

By FoxLearn 2/20/2024 6:34:33 AM   111
To implement file copy progress in C#, you can use the File.Copy method along with FileStream to read from the source file and write to the destination file while monitoring the progress.

You can achieve this by reading and writing chunks of data at a time and updating the progress accordingly.

This example shows how you can copy a file with progress tracking:

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string sourceFilePath = @"C:\path\to\source\file.txt";
        string destinationFilePath = @"C:\path\to\destination\file.txt";

        CopyFileWithProgress(sourceFilePath, destinationFilePath);

        Console.WriteLine("File copy completed.");
    }

    //c# file copy progress
    static void CopyFileWithProgress(string sourceFilePath, string destinationFilePath)
    {
        const int bufferSize = 8192; // 8 KB buffer size, you can adjust it as per your requirement

        using (var sourceStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
        using (var destinationStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write))
        {
            byte[] buffer = new byte[bufferSize];
            int bytesRead;
            long totalBytesCopied = 0;
            long fileSize = sourceStream.Length;

            while ((bytesRead = sourceStream.Read(buffer, 0, bufferSize)) > 0)
            {
                destinationStream.Write(buffer, 0, bytesRead);
                totalBytesCopied += bytesRead;

                // Calculate progress
                double progress = (double)totalBytesCopied / fileSize * 100;
                Console.WriteLine($"Progress: {progress:F2}%");
            }
        }
    }
}

- We open the source file and destination file using FileStream.

- We read from the source file in chunks and write those chunks to the destination file until we've read the entire file.

- We calculate the progress by comparing the total bytes copied with the total file size and print the progress to the console.

You can adjust the buffer size according to your requirements and even implement a progress bar or update a UI if you are working with a graphical application.