复制文件时显示复制进度实际上就是用文件流来复制文件,并在每一块文件复制后,用进度条来显示文件的复制情况,那么,如何通过编写c#源代码实现复制文件显示文件进度条呢?
关键代码:
class Program
{
static void Main(string[] args)
{
string sourcePath = @"./SourceFiles"; // 源文件夹路径
string destinationPath = @"./DestinationFiles"; // 目标文件夹路径
if (!Directory.Exists(sourcePath))
{
Console.WriteLine("源文件夹不存在,请先创建 SourceFiles 文件夹并放入文件。");
return;
}
if (!Directory.Exists(destinationPath))
{
Directory.CreateDirectory(destinationPath);
}
string[] files = Directory.GetFiles(sourcePath);
if (files.Length == 0)
{
Console.WriteLine("源文件夹为空,没有文件可复制。");
return;
}
Console.WriteLine("开始复制文件...");
int current = 0;
foreach (string file in files)
{
string fileName = Path.GetFileName(file);
string destFile = Path.Combine(destinationPath, fileName);
File.Copy(file, destFile, true); // 覆盖已有文件
// 更新进度条
UpdateProgress(current++, files.Length);
Thread.Sleep(100); // 模拟耗时操作,实际中可删除
}
Console.WriteLine("\n\n文件复制完成!");
}
static void UpdateProgress(int current, int total)
{
double percent = (double)current / total;
int barWidth = 50;
int filledBars = (int)(barWidth * percent);
string progressBar = new('█', filledBars) + new string('-', barWidth - filledBars);
Console.Write($"\r[{progressBar}] {percent:P0} ({current}/{total})");
}
}
评论