c# 复制文件夹中的所有文件夹与文件到另一个文件夹

来源:互联网 发布:win10平板手势软件 编辑:程序博客网 时间:2024/05/20 05:56
#region 文件夹操作
        /// <summary> //转载请注明来自 http://www.shang11.com
        /// 复制文件夹中的所有文件夹与文件到另一个文件夹
        /// </summary>
        /// <param name="sourcePath">源文件夹</param>
        /// <param name="destPath">目标文件夹</param>
        public static void CopyFolder(string sourcePath,string destPath)
        {
            if (Directory.Exists(sourcePath))
            {
                if (!Directory.Exists(destPath))
                {
                    //目标目录不存在则创建
                    try
                    {
                        Directory.CreateDirectory(destPath);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("创建目标目录失败:" + ex.Message);
                    }
                }
                //获得源文件下所有文件
                List<string> files = new List<string>(Directory.GetFiles(sourcePath));                
                files.ForEach(c =>
                {         
                    string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
                    File.Copy(c, destFile,true);//覆盖模式
                });
                //获得源文件下所有目录文件
                List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));                
                folders.ForEach(c =>
                {
                    string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
                    //采用递归的方法实现
                    CopyFolder(c, destDir);
                });                
            }
            else
            {
                throw new DirectoryNotFoundException("源目录不存在!");
            }            
        }
0 0
原创粉丝点击