复制文件夹

本文介绍了一个使用 C# 编写的递归函数 FolderCopy,该函数用于复制包含子目录的整个文件夹结构。它首先检查并确保目标路径正确,并在必要时创建缺失的目标目录。然后遍历源目录中的所有文件和子目录,复制文件并将只读属性的文件改为正常属性以便复制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 public void FolderCopy(string srcFolderPath, string destFolderPath)
        {
            //检查目标目录是否以目标分隔符结束,如果不是则添加之
            if (destFolderPath[destFolderPath.Length - 1] != Path.DirectorySeparatorChar)
                destFolderPath += Path.DirectorySeparatorChar;
            //判断目标目录是否存在,如果不在则创建之
            if (!System.IO.Directory.Exists(destFolderPath))
                System.IO.Directory.CreateDirectory(destFolderPath);
            string[] fileList = System.IO.Directory.GetFileSystemEntries(srcFolderPath);
            foreach (string file in fileList)
            {
                if (System.IO.Directory.Exists(file))
                    FolderCopy(file, destFolderPath + Path.GetFileName(file));
                else
                {
                    FileInfo fi = new FileInfo(file);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)//改变只读文件属性,否则删不掉
                        fi.Attributes = FileAttributes.Normal;
                    try
                    { File.Copy(file, destFolderPath + Path.GetFileName(file), true); }
                    catch (Exception e)
                    {
                        WriteNotepad(e.Message+"6");
                    }
                }
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值