[reprint] C ා copy all contents under the specified folder to the target folder

In the process of folder operation, sometimes it is necessary to copy all the contents under the folder to another folder. In the development of C ා sometimes it is necessary to copy all the contents under the specified folder to another folder. This process needs to traverse all the files and directories. This process also involves the use of Directory.CreateDirectory method to create folders, File.Copy method to copy files and other operations. The specific method is as follows:

      /// <summary>
        ///Specify all contents under the folder to copy to the target folder
        /// </summary>
        ///< param name = "srcpath" > original path < / param >
        ///< param name = "aimpath" > destination folder < / param >
        public static void CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // Check whether the target directory ends with a directory split character. 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 the file list of the source directory, which is an array of files and directory paths
                //If you point to a file under the copy target file without a directory, 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, treat it as a directory. If the directory exists, Copy the files under the directory recursively

                    if (Directory.Exists(file))
                        CopyDir(file, aimPath + Path.GetFileName(file));
                    //Otherwise, Copy the file directly
                    else
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                }
            }
            catch (Exception ee)
            {
                throw new Exception(ee.ToString());
            }
        }

  

Note: the original is reproduced from C ා copy all contents under the specified folder to the target folder ා IT technology fun house.

Tags: C#

Posted on Sat, 09 Nov 2019 08:36:26 -0800 by jcubie