stream.copyto与进度条报告

out*_*994 4 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");
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 6

您可以以块的形式读取文件.

你应该通知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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)