复制进度条不起作用

时间:2011-12-10 16:43:37

标签: c# copy progress-bar

我有点问题。我正在尝试创建一个表单,使用状态栏将东西从A点复制到B.现在复制工作正常,但状态栏只是没有做任何事情.. 有人有任何线索吗?

public partial class Form4A : Form
{
    public Form4A()
    {
        InitializeComponent();
        OtherSettings();
        BackgroundWorker.RunWorkerAsync(); // Starts wow copying
    }

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

        if (!Directory.Exists(SourcePath))
        {
            for (int i = 1; i <= 100; i++)
            {
                //Now Create all of the directories
                foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
                    SearchOption.AllDirectories))
                    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));

                //Copy all the files
                foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
                    SearchOption.AllDirectories))
                    File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath));


                BackgroundWorker.ReportProgress(i);
            }
        }
    }
    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // Change the value of the ProgressBar to the BackgroundWorker progress.
        progressBar1.Value = e.ProgressPercentage;
        // Set the text.
        this.Text = e.ProgressPercentage.ToString();
    }

}

1 个答案:

答案 0 :(得分:0)

你说:if (!Directory.Exists(DestinationPath))。这意味着如果存在desination路径,则永远不会执行循环。在测试代​​码之前,请确保删除DestinationPath!

编辑:

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);
    }
}