How to make a file copy progress in C#
By FoxLearn 2/20/2024 6:34:33 AM 516
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.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#
Categories
Popular Posts
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
Spica Admin Dashboard Template
11/18/2024