【问题标题】:Progressbar during folder copy文件夹复制过程中的进度条
【发布时间】:2019-06-16 02:15:14
【问题描述】:

我需要在文件夹复制(异步)时显示进度。
我可以使用单个文件副本来执行此操作,但不能使用文件夹...我只想像 Windows 一样显示整个副本的进度。

这是我复制文件夹的代码:

private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, CancellationToken cancellationToken)
{
    cancellationToken.ThrowIfCancellationRequested();
    DirectoryInfo dir = new DirectoryInfo(sourceDirName);

    DirectoryInfo[] dirs = dir.GetDirectories();
    // If the destination directory doesn't exist, create it.
    if (!Directory.Exists(destDirName))
    {
        Directory.CreateDirectory(destDirName);
    }

    if (!Directory.Exists(destDirName))
    {
        throw new DirectoryNotFoundException(
            "Source directory does not exist or could not be found: "
            + sourceDirName);
    }

    // Get the files in the directory and copy them to the new location.
    FileInfo[] files = dir.GetFiles();
    foreach (FileInfo file in files)
    {
        string temppath = Path.Combine(destDirName, file.Name);
        file.CopyTo(temppath, false);
    }

    // If copying subdirectories, copy them and their contents to new location.
    if (copySubDirs)
    {
        foreach (DirectoryInfo subdir in dirs)
        {
            string temppath = Path.Combine(destDirName, subdir.Name);
            DirectoryCopy(subdir.FullName, temppath, copySubDirs, cts.Token);
        }
    }
}

然后通过按钮调用:

await Task.Run(() => DirectoryCopy(
    srcFolder, 
    @"\\" + hostname + @"\C$\" + destFolder + @"\", 
    true, 
    cts.Token
));

我怎样才能做到这一点?

如果没有关于我的问题的足够信息,请告诉我,我会更新我的帖子。

【问题讨论】:

  • 欢迎来到 StackOverflow!您能否告诉我们到目前为止您尝试了什么和/或您遇到了什么错误?
  • 您在使用什么 - WPF / WinForms 或控制台应用程序?
  • 复制多个文件的自定义解决方案,此链接可能有助于了解基础知识:codeproject.com/Articles/36647/…
  • 对不起,我正在使用 WPF。感谢您的链接,但它不适用于我的需求:(

标签: c# copy directory


【解决方案1】:

您可以使用 IProgress 接口。

例如,

private async Task DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, CancellationToken cancellationToken,IProgress<int> progress)
{
    // Do work
    var percentageProgress = 0;
    // percentageProgress = Calculate percentage
    progress.Report(percentageProgress);
}

在客户端(相信你的按钮点击事件),

var progressIndicator = new Progress<int>(ShowProgress);
await UploadPicturesAsync(sourceDirName,destDirName,copySubDirs,token,progressIndicator);

ShowProgress 定义为

void ShowProgress(int value)
{
// Update UI
}

您也可以在 IProgress herehere 上阅读更多信息

【讨论】:

  • 感谢这个例子。我能问你一件事吗 ?考虑到我上面的代码,我该如何计算百分比?顺便说一句,我想这是我需要的解决方案:)
  • @Rems 也许我会以非递归方式进行。递归使得“衡量”进度变得更加困难。使用“SearchOption.AllDirectories”的非递归方法可能是更好的选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2011-08-28
  • 1970-01-01
  • 2012-12-23
  • 1970-01-01
  • 2012-12-05
  • 2010-11-20
相关资源
最近更新 更多