C # does not copy the entire folder. If you need to copy it recently, I wrote a demo to share it with you.
Main ideas:
1. Write a copy folder function copyfolder, which is passed to the source folder path and destination folder path.
2. Check whether the destination folder path exists. If not, create this folder.
3. obtain all the files in the source folder and copy these files to the target folder.
4. obtain all the folders in the source folder and call copyfolder cyclically (recursion is used here)
Code:
Copy folder
Using system;
Using system. IO;
Namespace folderservice
{
Public class folderservice
{
Static void main (string [] ARGs)
{
If (ARGs. length! = 2)
{
Console. writeline ("Enter the source folder address and destination folder address! ");
Return;
}
// Determine whether the source folder exists
If (! Directory. exists (ARGs [0])
{
Console. writeline ("the source folder does not exist! ");
Return;
}
// Copy a folder
Folderservice copy = new folderservice ();
String flag = copy. copyfolder (ARGs [0], argS [1]);
Console. writeline (FLAG );
}
/// <Summary>
/// Copy folder
/// </Summary>
/// <Param name = "Spath"> source folder path </param>
/// <Param name = "dpath"> destination folder path </param>
/// <Returns> completion status: Success-complete; Other-error </returns>
Public String copyfolder (string Spath, string dpath)
{
String flag = "success ";
Try
{
// Create a destination folder
If (! Directory. exists (dpath ))
{
Directory. createdirectory (dpath );
}
// Copy an object
Directoryinfo sdir = new directoryinfo (Spath );
Fileinfo [] filearray = sdir. getfiles ();
Foreach (fileinfo file in filearray)
{
File. copyto (dpath + "\" + file. Name, true );
}
// Loop subfolders
Directoryinfo ddir = new directoryinfo (dpath );
Directoryinfo [] subdirarray = sdir. getdirectories ();
Foreach (directoryinfo subdir in subdirarray)
{
Copyfolder (subdir. fullname, dpath + "//" + subdir. Name );
}
}
Catch (exception ex)
{
Flag = ex. tostring ();
}
Return flag;
}
}
}
Test DMO:
1. Save the code as folderservice. CS and put the CS file under H: \ Program Files \ Microsoft Visual Studio 9.0 \ Vc (the address varies depending on the vs installation path)
2. Open Visual Studio 2008 command prompt in Visual Studio Tools, drag folderservice. CS to the command prompt, add CSC + space at the beginning of the path, and press enter to compile the program, for example:
3. In the directory H: \ Program Files \ Microsoft Visual Studio 9.0 \ vc, you can see that a folderservice.exefile is generated, run this file (Open cmd.exe, drag folderservice.exeto cmd.exe, add the parameter, and press Enter), for example:
4. Now we can see that all the files in the E: \ test directory are copied to the G: \ test directory.