复制文件时显示复制文件进度,其实就是用文件流来复制文件,并在每一块文件复制后,用进度条显示文件的复制情况,下面,济南网站建设小编就来为大家介绍,如何通过编写c#源代码实现复制文件显示复制进度?有需要的朋友可以过来参考一下
关键代码:
class Program
{
static void Main()
{
string sourceFilePath = @"C:\path\to\source\file.txt";
string destinationFilePath = @"C:\path\to\destination\file.txt";
try
{
CopyFileWithProgress(sourceFilePath, destinationFilePath);
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
}
}
static void CopyFileWithProgress(string sourceFilePath, string destinationFilePath)
{
using (FileStream sourceStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
{
long fileLength = sourceStream.Length;
using (FileStream destinationStream = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write))
{
byte[] buffer = new byte[1024 * 1024]; // 使用1MB缓冲区
int bytesRead;
long totalBytesRead = 0;
while ((bytesRead = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
destinationStream.Write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
// 计算并输出百分比进度
double progressPercentage = (double)totalBytesRead / fileLength * 100;
Console.Write($"\r复制进度: {progressPercentage:F2}%");
}
Console.WriteLine(); // 打印完成信息后换行
}
}
Console.WriteLine("文件复制完成!");
}
}
评论