文件夹复制过程中的进度条

时间:2019-01-22 15:08:57

标签: c# copy directory

我需要在复制文件夹(异步)时显示进度。
我可以使用单个文件副本来执行此操作,但不能使用文件夹来执行此操作……我只想像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
));

我该如何实现?

如果没有足够的信息来告诉我,我会更新我的帖子。

1 个答案:

答案 0 :(得分:3)

您可以使用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的更多信息

相关问题