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");
}
}
}
}
{
//检查目标目录是否以目标分隔符结束,如果不是则添加之
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");
}
}
}
}
本文介绍了一个使用 C# 编写的递归函数 FolderCopy,该函数用于复制包含子目录的整个文件夹结构。它首先检查并确保目标路径正确,并在必要时创建缺失的目标目录。然后遍历源目录中的所有文件和子目录,复制文件并将只读属性的文件改为正常属性以便复制。
1713

被折叠的 条评论
为什么被折叠?



