gpt4 book ai didi

c# - 使用字节复制文件+进度条

转载 作者:行者123 更新时间:2023-11-30 18:02:00 25 4
gpt4 key购买 nike

我正在尝试在我的文件复制表单上添加进度,它可以正常工作,但进度条会根据文件数量进行更新。问题是有很多小文件,还有一些非常大的文件需要复制。

所以我想知道是否有一种方法可以检查写入的字节数而不是使用文件号。非常感谢任何建议。这是我现在的代码:

    private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string SourcePath = RegistryRead.ReadOriginalPath();
string DestinationPath = RegistryRead.ReadNewPath();

if (Directory.Exists(SourcePath))
{
//Now Create all of the directories
string[] allDirectories = Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories);
string[] allFiles = Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories);
int numberOfItems = allDirectories.Length + allFiles.Length;
int progress = 0;

foreach (string dirPath in allDirectories)
{
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
progress++;
BackgroundWorker.ReportProgress(100 * progress / numberOfItems);
}

//Copy all the files
foreach (string newPath in allFiles)
{
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));
progress++;
BackgroundWorker.ReportProgress(100 * progress / numberOfItems);
}
}

}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
}

提前致谢

最佳答案

如果你想自己做,你可以

  1. 遍历所有文件,计算要复制的总大小。
  2. 调用 CopyFileEx 进行复制。这使用回调机制来报告进度,并且该回调包括为当前文件复制的字节数。
  3. 跟踪总共复制了多少字节,并使用它来报告总体进度。

很可能有一个 .net 管理的等同于 CopyFileEx。

不过,我建议您调用 SHFileOperation让系统为您完成艰苦的工作。当你发现这个任务非常难以做好时。作为使用 shell 完成工作的额外好处,您将获得标准系统对话框。

关于c# - 使用字节复制文件+进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8467180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com