Copy all directories and files in a directory

xiaoxiao2021-03-06  53

This article describes how to copy all files in a directory to the target directory.

Let's introduce a few classes we want to use in this routine:

1, Directory: Exposes Static Methods for Creating, Moving, and Enumerating Through Directories and Subdirectories.

2, PATH: Performs Operations On String Instances That Contain File or Directory Path Information. These Operations Are Performed in A Cross-Platform Manner.

3, FILE: Provides Static Methods for the Creation, Copying, Deletion, Moving, And Opening of Files, And Aids in The Creation of FileStream Objects.

These two classes are not inherited, and it is directly inherited from Object, and it is implemented as Sealed, and the above explanation is from MSDN.

The following is the code implemented, the details in the code are not described in detail here, please see the code annotation:

/ / =========================================================================================================================================================================================== ======

/ / Implement a static method to copy all the contents below the specified folder below to the target folder

/ / =========================================================================================================================================================================================== ======

Public Static Void CopyDir (String Srcpath) {

/ / Check if the target directory ends with directory segmentation characters if not added

IF (aimpath [aimpath.length-1]! = path.directoryseparatorchar)

Aimpath = path.directoryseparatorchar;

/ / Judgment if the target directory exists if there is no existence, new

IF (! Directory.exists (aimpath)) Directory.createdIRectory (AIMPATH);

/ / Get a list of files of the source, which is an array containing files and directory paths.

// If you point to the file under the COPY target file without including a 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) {// first as a directory processing If there is this directory, recursively copy the file below this directory.

IF (Directory.exists (file))

CopyDir (File, Aimpath path.getFileName (file));

/ / Otherwise directly copy file

Else

File.copy (File, Aimpath Path.GetFileName (file), true);

}

}

转载请注明原文地址:https://www.9cbs.com/read-118165.html

New Post(0)