文件可以批量复制吗?c#批量复制文件显示进度条示例代码(控制台程序)

济南云服务器 2025年7月8日10:29:45C#教程文件可以批量复制吗?c#批量复制文件显示进度条示例代码(控制台程序)已关闭评论1831阅读模式

复制文件时显示复制进度实际上就是用文件流来复制文件,并在每一块文件复制后,用进度条来显示文件的复制情况,那么,如何通过编写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})");
    }
}

济南云服务器
  • 本文由 发表于 2025年7月8日10:29:45
  • 转载请务必保留本文链接:http://news.hcsw666.com/2126