1 回答
TA贡献1820条经验 获得超9个赞
如果我理解正确,您指定了以下源目录和目标目录:
var source = @"C:\TestArea\Destination\SUP000001\20041202 - 01 - 0002 - 001\NAC";
var dest = @"C:\TestArea\Destination\SUP000001\20041202-01-0002-001";
并且您想将NAC目录(连同它的所有内容)从目录复制source到destination目录,但问题是NAC目录的内容被直接复制到20041202-01-0002-001文件夹中,而您真的想得到如下路径(并且此NAC目录应与源NAC目录相同):
@"C:\TestArea\Destination\SUP000001\20041202-01-0002-001\NAC"
如果是这种情况,那么您只需要首先通过将源目录的名称添加到目标目录路径来修改它,如下所示:
destination = Path.Combine(destination, sourceDir.Name);
这是一个可以解决问题的代码示例:
private static void CopyDirectory(string source, string destination)
{
var sourceDir = new DirectoryInfo(source);
if (!sourceDir.Exists) throw new DirectoryNotFoundException(nameof(source));
// Add last directory of source to destination and create it
destination = Path.Combine(destination, sourceDir.Name);
Directory.CreateDirectory(destination);
// Copy files from source to destination
foreach (var file in sourceDir.GetFiles())
{
file.CopyTo(Path.Combine(destination, file.Name));
}
// Recursively copy sub directories from source to destination
foreach (var subDir in sourceDir.GetDirectories())
{
CopyDirectory(subDir.FullName, destination);
}
}
- 1 回答
- 0 关注
- 120 浏览
添加回答
举报