C # how to specify that everything under the folder is copied to the destination folder
This article is about how C # specifies all the contents under the folder to be copied to the target folder. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
In the process of folder operation, it is sometimes necessary to copy all the contents under the folder to another folder. In the development of C#, it is sometimes encountered that all the contents under the specified folder will be copied to another folder. This process requires traversing all files and directories. This process also involves using the Directory.CreateDirectory method to create folders, the File.Copy method to copy files, and so on. The specific method implementation is as follows:
/ / /
/ / copy all the contents under the specified folder to the destination folder
/ / /
/ original path
/ / destination folder
Public static void CopyDir (string srcPath, string aimPath)
{
Try
{
/ / check whether the target directory ends with directory split characters. If not, add it.
If (aimPath [aimPath.Length-1]! = Path.DirectorySeparatorChar)
AimPath + = Path.DirectorySeparatorChar
/ / determine whether the target directory exists. If not, create a new directory.
If (! Directory.Exists (aimPath))
Directory.CreateDirectory (aimPath)
/ / get a list of files in the source directory, which is an array containing files and directory paths
/ / if you point to the file under the copy object file without including the directory, please use the following method
/ / string [] fileList = Directory.GetFiles (srcPath)
String [] fileList = Directory.GetFileSystemEntries (srcPath)
/ / traverse all files and directories
Foreach (string file in fileList)
{
/ / treat it as a directory first. If this directory exists, recursively Copy the files under that directory.
If (Directory.Exists (file))
CopyDir (file, aimPath + Path.GetFileName (file))
/ / otherwise, direct Copy file
Else
File.Copy (file, aimPath + Path.GetFileName (file), true)
}
}
Catch (Exception ee)
{
Throw new Exception (ee.ToString ())
}
}
Thank you for reading! This is the end of this article on "how to specify how to copy all the contents under the folder to the target folder". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!