欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#深拷贝文件夹示例

程序员文章站 2023-12-18 21:20:52
复制代码 代码如下:using system;using system.collections.generic;using system.io;using system.l...

复制代码 代码如下:

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();
        }
    }
}

上一篇:

下一篇: