Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Copying Files in C# 1

Status
Not open for further replies.

Kenny100

Technical User
Feb 6, 2001
72
0
0
NZ
Hi All

How do I copy all of the files from one directory (e.g. C:\test) to another directory (e.g. C:\test2) using C#?

I've tried using the public static void Copy() method with little success.

Cheers,
Kenny.
 
Hello Kenny,

I was able to copy an entire directory of files over to another directory using this code:
Code:
test = System.IO.Directory.GetFiles("C:\\test1");

foreach(string t in test)
{
	System.IO.File.Copy(t, "f:\\test2\\" + System.IO.Path.GetFileName(t) );

	//TextBox required for the following line to work
	//Shows each file in the directory
	//textBox1.AppendText(t + (char) 13 + (char) 10);
}
This code just copies the files in the given directory, not including the subdirectories.

Feel free to post if you have any questions. I hope this helps! -Dave
 
Thanks djones7936 - I wish I had the brains of a programmer!

Anyway, your solution works great. However, if I now wanted to copy ALL files AND subdirectories can I make a simple modification to this code or will that involve a completely new method?

Cheers,
Kenny.
 
Hi Kenny,

I thought you might want that. I made a subroutine that does just that.

Settle in, this will be a long one... ;-)

Getting all the files in one directory is one thing, but getting all the files in all the subdirectories is another thing.

There is a function called "System.IO.Directory.GetDirectories" that you use just like System.IO.Directory.GetFiles. Unfortunately, those two functions alone only return the files and subdirectories of just ONE folder; It doesn't include the subdirectory's files or it's subdirectories.


Lets say C:\test has test1A and test2A as subdirectories.
and the "test1A" subdirectory has the subdirectories "test1B" and "test2B".

c:\test

c:\test\test1A
c:\test\test1A\test1B
c:\test\test1A\test2B

c:\test\test2A

Lets say
string tempstr = System.IO.Directory.GetDirectories("c:\\test");
tempstr would equal "c:\test\test1A", and "c:\test\test2A".
(only c:\test's subdirectories)

If you were to take the output stored in tempstr (the subdirectories of "c:\test") and put it back into the GetDirectories() command, you would get the subdirectories of "c:\test\test1A" (which would be "c:\test\test1A\test1B" and "c:\test\test1A\test2B") and the subdirectories of "c:\test\test2A" (none). If you add that to the first time you call the function, then you would then have all of the subdirectories of "c:\test" two levels away, (and in this example, every single directory). GetDirectories() could, in effect, be recursively called again and again to get every level subdirectory. This idea is called recursive programming. For more info on this, search "recursive function calling" at
Once you have a list of every subdirectory, you would have to replicate the subdirectories from the source directory in the destination directory before you could copy the files over to the destination.

With those two ideas in mind, I made the subroutine.
Code:
private void CopyAllFiles(string strSourcedirectory, string strDestinationDirectory, bool bCheckSubdir)
		{
			//Debugging Statement - Allows you to see which variables are passed in
			//to the subroutine
			//MessageBox.Show("Input Vars: " + strSourcedirectory + ", " + strDestinationDirectory + ", " + bCheckSubdir);

			string foldername, newDestDir;

			//If the destination directory doesn't exist, then create it
			if(System.IO.Directory.Exists(strDestinationDirectory) == false)
			{
				System.IO.Directory.CreateDirectory(strDestinationDirectory);
				//textBox1.AppendText("New Directory1: " + strDestinationDirectory + (char) 13 + (char) 10);
			}

			if(bCheckSubdir)
			{
				//local variable
				string[] ListOfSubdirectories= System.IO.Directory.GetDirectories(strSourcedirectory); 
				foreach(string dir in ListOfSubdirectories)
				{
					//the folder name of the subdirectory
					foldername = dir.Substring(strSourcedirectory.Length+1, dir.Length-strSourcedirectory.Length-1);

					//The new destination directory
					newDestDir = strDestinationDirectory + "\\" + foldername;

					//If the destination directory doesn't exist, then create it
					if(System.IO.Directory.Exists(newDestDir) == false)
					{
						System.IO.Directory.CreateDirectory(newDestDir);
						//textBox1.AppendText("New Directory2: " + newDestDir + (char) 13 + (char) 10);
					}

					CopyAllFiles(dir, newDestDir, bCheckSubdir);
				}
			}

			//Get the list of files in the current directory
			string [] ListOfFiles = System.IO.Directory.GetFiles(strSourcedirectory);
			foreach(string fil in ListOfFiles)
			{
				//This is where you would add your file condition code
				//e.g. Copy the file only if the two file's time and date
				//      are different

				System.IO.File.Copy(fil, strDestinationDirectory + "\\" + System.IO.Path.GetFileName(fil) );
				//textBox1.AppendText("File Copy: (" + fil + ", " + strDestinationDirectory + "\\" + System.IO.Path.GetFileName(fil) + ")" + (char) 13 + (char) 10);
			}
		}
Hang in there, almost done!

Although this code has only about 15 lines of effective code, it is very powerful. ***I would recommend uncommenting the 3 textBox statements and MessageBox statement to see what is going on in the subroutine.***

The code takes 3 parameters: source directory (string), destination directory (string), and whether or not to recursively seek all of the subdirectories (boolean).

Pseudo Code
If the destination directory doesn't exist, then create it.

If the subroutine should check for subdirectories (as indicated by bCheckSubdir) then ...
Get a list of all the subdirectories in the folder.
With each subdirectory,
#1 get just it's name (without the path leading up to it)
#2 Determine what the it's path would be in the destination folder.
#3 If the folder doesn't exist create it.
#4 Once the Folder is created, (this is the tricky part) then it is okay to go into the newly created folder. (CopyAllFiles is called again with the newly created folder. The current CopyAllFiles subroutine is put on hold and resumes after the newly called CopyAllFiles completes.)

Once every subdirectory is created for a particular folder, then transfer the files.
Get a list of all the files in CopyAllFiles' current directory.
visit each file on the list then copy the file over.

The recursive part, #4 is the trickest part. The subroutine is sort of like a subdirectory. For every subdirectory, CopyAllFile is called once. Because, functions can call themselves, different instances of CopyAllFiles can be run at the same time. Just as a subdirectory can be 3 or 4 directory deep from the root directory, the CopyAllFile can be 3 or 4 calls deep.

If you don't know about recursive functions, then if you read up on it, this post will make a lot more sense.

Anyways, here is an example how to run the subroutine:
Code:
CopyAllFiles("c:\\sourceDir", "c:\\destDir", true);
true means recursively copy ALL subdirectories and ALL files from the sourceDir directory
false means copy only the files in the sourceDir directory

The code can be called from a button or from Form_Load. Make sure, when you test it, not to copy too large of files, or it will take a long time to see the results.

This post was a good chance for me to learn C# syntax and the way C# does things.

Do I dare say? Ask if you have any questions! [peace] -Dave
 
Wow, wow, wow! Thanks for all of your hard work djones7936. I should get a chance to implement this tonight after work ... can't wait! :)

Cheers,
Kenny.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top