关闭

C# 目录(文件夹)复制实现

34人阅读 评论(0) 收藏 举报
分类:

C#文件夹目录复制的核心代码:

private static void CopyDir(DirectoryInfo origin, string target)
        {
            if (!target.EndsWith("\\"))
            {
                target += "\\";
            }
            if (!Exist(target))
            {
                Create(target);
                //Create(target, origin.GetAccessControl());
            }
            FileInfo[] fileList = origin.GetFiles();
            DirectoryInfo[] dirList = origin.GetDirectories();
            foreach (FileInfo fi in fileList)
            {
                File.Copy(fi.FullName, target + fi.Name, true);
            }
            foreach (DirectoryInfo di in dirList)
            {
                CopyDir(di, target + di.Name);
            }
            DirectoryInfo tmp = new DirectoryInfo(target);
            tmp.Attributes = origin.Attributes;
            tmp.SetAccessControl(origin.GetAccessControl());
        }

        private static void CopyDir(string origin, string target)
        {
            if (!origin.EndsWith("\\"))
            {
                origin += "\\";
            }
            if (!target.EndsWith("\\"))
            {
                target += "\\";
            }

            DirectoryInfo info = new DirectoryInfo(origin);
            if (!Exist(target))
            {
                Create(target,info.GetAccessControl());//创建目录,访问权限
            }

            FileInfo[] fileList = info.GetFiles();
            DirectoryInfo[] dirList = info.GetDirectories();
            foreach (FileInfo fi in fileList)
            {
                File.Copy(fi.FullName, target + fi.Name, true);
            }
            foreach (DirectoryInfo di in dirList)
            {
                //CopyDir(origin + "\\" + di.Name, target + "\\" + di.Name);
                CopyDir(di.FullName, target + "\\" + di.Name);
            }
            //设置目录属性和访问权限
            DirectoryInfo tmp = new DirectoryInfo(target);
            tmp.Attributes = info.Attributes;
            tmp.SetAccessControl(info.GetAccessControl());
        }


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:36次
    • 积分:10
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档