c#拷贝文件夹 c#深拷贝文件夹示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

c#拷贝文件夹 c#深拷贝文件夹示例

  2021-03-19 我要评论
想了解c#深拷贝文件夹示例的相关内容吗,在本文为您仔细讲解c#拷贝文件夹的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:拷贝文件夹,下面大家一起来学习吧。

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace FileUtility
{
    public class Program
    {
        public static void DeepCopy(DirectoryInfo source, DirectoryInfo target, params string[] excludePatterns)
        {
            if (target.FullName.Contains(source.FullName))
                return;

            // Go through the Directories and recursively call the DeepCopy Method for each one
            foreach (DirectoryInfo dir in source.GetDirectories())
            {
                var dirName = dir.Name;
                var shouldExclude = excludePatterns.Aggregate(false, (current, pattern) => current || Regex.Match(dirName, pattern).Success);

                if (!shouldExclude)
                    DeepCopy(dir, target.CreateSubdirectory(dir.Name), excludePatterns);
            }

            // Go ahead and copy each file to the target directory
            foreach (FileInfo file in source.GetFiles())
            {
                var fileName = file.Name;
                var shouldExclude = excludePatterns.Aggregate(false,
                                                              (current, pattern) =>
                                                              current || Regex.Match(fileName, pattern).Success);

                if (!shouldExclude)
                    file.CopyTo(Path.Combine(target.FullName, fileName));
            }
        }

        static void Main(string[] args)
        {
            DeepCopy(new DirectoryInfo(@"d:/test/b"), new DirectoryInfo(@"d:/test/a"));
            DeepCopy(new DirectoryInfo(@"d:/test/c"), new DirectoryInfo(@"d:/test/c/c.1"));
            DeepCopy(new DirectoryInfo(@"d:/test/1/"), new DirectoryInfo(@"d:/test/2/"), new string[] { ".*\\.txt" });

            Console.WriteLine("复制成功...");
            Console.ReadKey();
        }
    }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们