简体   繁体   中英

C# working with progress bar while copying a file

Does anyone have an example of working with a progress bar while copying a file, or can direct me to a place where this question has been asked?

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

The above is the code I have used so far. It works but doesn't really give me what I want. I am looking for a way to make the progress bar update as the file is copying, so that the progress bar will keep moving until the file has finished copying.

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

(probably I misunderstood you, because you want the bar move on even on a single big file? If that is the case, I have no quick solution for you and even Windows does not manage it within file explorer)

MSDN is your friend:

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

You will need to implement the copy code yourself (you can't use FileCopy or similar commands). For an example of how you'd do this, see this article .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM