Click here to Skip to main content
16,012,168 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi,

I have a code that copy files and nested folder to another location and i want to show the progress bar with that. How can i do that?????????????Any suggestion/idea or if somebody give me piece of code so that may be i'll embed with it????
Please see the Code is shown below:
C#
class CopyDir
   {
       public static void Copy(string sourceDirectory, string targetDirectory)
       {
           DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
           DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

           CopyAll(diSource, diTarget);
       }

       public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
       {

           // Check if the target directory exists, if not, create it.
           if (Directory.Exists(target.FullName) == false)
           {
               Directory.CreateDirectory(target.FullName);
           }

           // Copy each file into it's new directory.
           foreach (FileInfo fi in source.GetFiles())
           {
               //Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
               fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);

           }

               // Copy each subdirectory using recursion.
               foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
               {

   DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);

                   CopyAll(diSourceSubDir, nextTargetSubDir);

               }
       }
   }
Posted
Updated 14-Dec-11 9:33am
v2

Your best bet is to show progress in terms of how many files have been copied. It's a lot more work than it's worth to do it by amount of data copied. However, if that's what you want to do, I recommend that you google the FileSystemWatcher object, and see if that won't do what you want.
 
Share this answer
 
Comments
AAMERSAEED 14-Dec-11 15:36pm    
Actually i want to show a progress bar with a specified percent complete or number of bytes or time remaining?????????????
Also one approach is to enumerate all the files to be copied first and then sum the bytes you're going to copy. After each file copy get the byte amount copied (file size) and update the progress bar based on that.
 
Share this answer
 
Comments
AAMERSAEED 14-Dec-11 15:46pm    
Any piece of code because i am a student and in learning process so if you could help me please?
Wendelius 14-Dec-11 16:07pm    
You already have the CopyAll-method where you use FileInfo when you iterate through files. Create for example another method that first iterates through the files and gets FileInfo.Length Property [^]. Sum all the lengths when iterating the files. Now you should have the total amount of bytes to copy (files may be added or removed etc meanwhile so the amount isn't accurate). Pass that to the CopyAll method and in that method again sum the lengths of the files you have copied. These two numbers together should give you the estimated percentage of copied files
AAMERSAEED 15-Dec-11 16:38pm    
Yes i've got your point that we get the total bytes but Then how i know about the files that are copied to destination directory i.e how can i get the remaining bytes and keep the progress bar ticking.????????
Wendelius 15-Dec-11 16:56pm    
If you pass the total bytes to CopyAll as a parameter (lets say the value is 100) and you calculate the sum of copied bytes in your iteration after the copy operation, you can calculate the completed percentage i.e.
- file 1, size 100, total copied 100, progress 10%
- file 2, size 200, total copied 300, progress 30%
- file 3, size 500, total copied 800, progress 80%...
AAMERSAEED 17-Dec-11 8:50am    
Another question if you don't mind please tell me how can i control the progress bar because I've placed this recursive function of copy nested folder in the separate class named "CopyDir" and all the methods are static as well........so basically there are two classes 1. Form class which contains the progress bar 2. CopyDir class.
what to do so that progress bar keep ticking. Should i pass the progress bar as or the whole form to the CopyDir class??????????????
Since this is a bit different thing I added a new solution. The event handling could be something like:
C#
public class ProgressEventArgs : System.EventArgs {

   public decimal Percentage { get; set; }

   public ProgressEventArgs(decimal percentage)
      : base() {
      this.Percentage = percentage;
   }
}

public static class CopyDir {

   public static event System.EventHandler<ProgressEventArgs> ProgressChanged;
   public static bool CopyAll() {

      // This would be the actual copy iteration and percentage calculation
      for (decimal counter= 1;counter <= 10;counter++) {
         if (ProgressChanged != null) {
            ProgressChanged(null, new ProgressEventArgs((counter/10)*100));
         }
      }

      return true;
   }
}

and on your form you wire the event:
C#
public Form1() {
   InitializeComponent();

   CopyDir.ProgressChanged += new EventHandler<ProgressEventArgs>(CopyDir_ProgressChanged);
}

void CopyDir_ProgressChanged(object sender, ProgressEventArgs e) {
   this.progressBar1.Value = (int)e.Percentage;
}
 
Share this answer
 
Comments
AAMERSAEED 18-Dec-11 18:42pm    
Hi Mika Wendelius,
First of all thanks for the cooperation. This is what i am doing and it is working but the problem is that some time progress bar stuck at the end specifically when it comes to those files which are smaller in size. Can i post the image here also??
<pre lang="c#">
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;


namespace ProgressBarWithinClass
{
class ClassDir
{

static int maxbytes = 0;
static int copied = 0;
static int total = 0;

public static void Copy1(Label label1,ProgressBar progressBar1,string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
GetSize(diSource, diTarget);
maxbytes = maxbytes / 1024;

progressBar1.Maximum = maxbytes;
CopyAll(label1,progressBar1,diSource, diTarget);


}
public static void CopyAll(Label lable1, ProgressBar progressBar1,DirectoryInfo source, DirectoryInfo target)
{

if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
foreach (FileInfo fi in source.GetFiles())
{

fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);

total += (int)fi.Length;

copied += (int)fi.Length;
copied /= 1024;
progressBar1.Step = copied;
// progressBar1.Value=copied;
progressBar1.PerformStep();


lable1.Text = (total / 1024).ToString() + "KB of " + maxbytes.ToString() + "KB copied";
lable1.Refresh();



}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{



DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);

CopyAll(lable1, progressBar1, diSourceSubDir, nextTargetSubDir);
}

}

public static void GetSize(DirectoryInfo source, DirectoryInfo target)
{


foreach (FileInfo fi in source.GetFiles())
{
maxbytes += (int)fi.Length;

}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
GetSize(diSourceSubDir, nextTargetSubDir);

}
}

}
}
</pre>
And this is separate class i.e Form Class

<pre lang="c#">


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;



namespace ProgressBarWithinClass
{
public partial class Form1 : Form
{
ProgressBar pBar;
Form mainform;
Label l;

public Form1()
{
InitializeComponent();
pBar = new ProgressBar();
pBar.Location = new System.Drawing.Point(20, 20);
pBar.Name = "progressBar1";
pBar.Width = 200;

pBar.Height = 30;
Controls.Add(pBar);
l = new Label();
l.Name = "label1";
l.Location = new System.Drawing.Point(50,50);
l.Height=50;
Controls.Add(l);







}

private void copybtn_Click(object sender, EventArgs e)
{
ClassDir.Copy1(l,pBar,@"D:\Sajjad", @"E:\copydata");
//CopyDir.GetInfo();
Wendelius 18-Dec-11 23:56pm    
There's no place for images as far as I know. Have you debugged it? if you hit ctrl+break, where does the debugger go to? Could it be that there have been changes in the directory while you're copying?
AAMERSAEED 19-Dec-11 12:44pm    
Actually now i am at home and i've win xp on my pc and i check this progress bar is working well i've checked it on 200 kb folder but in university on window 7 it appears that progress bar not finishes but stop just one step before.ie slightly before the end point??????Also suggest me if what i am doing above in this application is correct approach or not??? because i've also heard about background worker that is used for progress bars???????if i use that i don't know which code of my current application should be placed in Do_Work event???????How ever i know that do_work event contains that code which is hard task and needs to run in the background??????Please suggest me the professional way???I will always appreciate your help as your suggestion in this regard is helpfull for me.
Member 10850253 16-Sep-16 14:19pm    
Is there a way to check if the subdirectories in the source folder exist in the destination folder, so that the files from the source replace the ones in the destination, in the folders that already exist?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900