How to copy all directories and files in a directory

xiaoxiao2021-03-06  113

Author:

Cuike519 column

http://blog.9cbs.net/cuike519/

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.GetFileSystem "; // Traverse all files and directories

Foreach (string file in filelist) {

// Before the 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);

}

}

Hey! This time, it is relatively simple, suitable for beginners, I hope to help beginners! If you need to use this feature in a web project, then set it to the ASPNET account enough permissions, but doing this is very dangerous, it is not recommended.

If you have any questions or suggestions you can send an email to: wu_jian830@hotmail.com

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

New Post(0)