c# - 带有进度条报告的 stream.copyto

标签 c#

我想合并 2 个大文件但是 atm 我的代码只在复制 1 个文件后更新进度有没有更好的方法来报告进度这是我的复制代码 atm

 max = files.Count;
 MessageBox.Show("Merge Started");
 using (Stream output = File.OpenWrite(dest))
   {
      foreach (string inputFile in files)
        {
          using (Stream input = File.OpenRead(inputFile))
            {
              input.CopyTo(output);
              count++;
              progress = count * 100 / max;
              backgroundWorker2.ReportProgress(Convert.ToInt32(progress));
            }
        }
  }
MessageBox.Show("Merge Complete");

最佳答案

您可以分块读取文件。

你应该通知中间的BackgroundWorker

using (Stream output = File.OpenWrite(dest))
{
    foreach (string inputFile in files)
    {
        using (Stream input = File.OpenRead(inputFile))
        {
            byte[] buffer = new byte[16 * 1024];

            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);

                // report progress back
                progress = (count / max + read / buffer.Length /* part of this file */) *  100;
                backgroundWorker2.ReportProgress(Convert.ToInt32(progress));
            }

            count++;
            progress = count * 100 / max;
            backgroundWorker2.ReportProgress(Convert.ToInt32(progress));
        }
    }
}

关于c# - 带有进度条报告的 stream.copyto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22857713/

相关文章:

c# - 如何在无尽的跑酷游戏中与火箭一起移动相机

c# - 类嵌套和访问修饰符

c# - 绑定(bind)到 Nullable Int32 时的绑定(bind)表达式错误

C#支持长路径的I/O库(解决PathTooLongException)

c# - 我可以在没有管理员权限的情况下保存到哪个存储库?

c# - 如何通过 ASP.NET Web API 使用 Active Directory 身份验证?

c# - 为什么我的 2D 子弹的碰撞器没有与任何东西碰撞?

c# - 列表<类>() 与列表<类>(0)

c# - ASP.NET MVC ViewModel 和 DropDownList

c# - 创建一个从在线提要中提取 NuGet 引用的 Visual Studio 项目模板