C#在复制文件时使用进度条

时间:2015-09-15 19:37:54

标签: c# progress-bar

有没有人在复制文件时有一个使用进度条的示例,或者可以将我引导到有问题的地方?

    private void Transferfiles(DirectoryInfo source, DirectoryInfo target)
    {
        int e = 0
        if (Directory.Exists(target.FullName) == false)
        {

                Directory.CreateDirectory(target.FullName);

        }
        foreach (FileInfo eachhfile in source.GetFiles())
        {
                eachhfile.CopyTo(Path.Combine(target.ToString(), eachhfile .Name));
                BytesToKilobytes += ((eachhfile .Length / 1024) / 1024);
                e = BytesToKilobytes ;
                backgroundWorker1.ReportProgress(e); 
        }
        foreach (DirectoryInfo SubDirectory in source.GetDirectories())
        {
                DirectoryInfo newTargetDirectory =
                    target.CreateSubdirectory(diSourceSubDir.Name);
                Transferfiles(SubDirectory, newTargetDirectory );
        }
    }

以上是我到目前为止使用的代码。它有效,但并没有真正给我我想要的东西。我正在寻找一种方法,以便在文件复制时更新进度条,以便进度条将一直移动,直到文件完成复制。

3 个答案:

答案 0 :(得分:1)

您可以检查要将其移动到的文件夹的大小,并将其用作进度条的当前值。

答案 1 :(得分:0)

(可能是我误解了你,因为你想要在一个大文件上移动吧?如果是这样的话,我没有你的快速解决方案,甚至Windows也无法在文件浏览器中管理它)

MSDN是你的朋友:

https://msdn.microsoft.com/de-de/library/system.windows.forms.progressbar(v=vs.110).aspx

private void CopyWithProgress(string[] filenames)
    {
        // Display the ProgressBar control.
        pBar1.Visible = true;
        // Set Minimum to 1 to represent the first file being copied.
        pBar1.Minimum = 1;
        // Set Maximum to the total number of files to copy.
        pBar1.Maximum = filenames.Length;
        // Set the initial value of the ProgressBar.
        pBar1.Value = 1;
        // Set the Step property to a value of 1 to represent each file being copied.
        pBar1.Step = 1;

        // Loop through all files to copy.
        for (int x = 1; x <= filenames.Length; x++)
        {
            // Copy the file and increment the ProgressBar if successful.
            if(CopyFile(filenames[x-1]) == true)
            {
                // Perform the increment on the ProgressBar.
                pBar1.PerformStep();
            }
        }
    }

答案 2 :(得分:0)

您需要自己实现复制代码(不能使用FileCopy或类似的命令)。有关如何执行此操作的示例,请参阅this article