即使目录为空,如何将目录从源复制到目标?

时间:2016-04-08 08:28:04

标签: c# io

遵循此结构。

A
 A1
   A111
 A2
 A3
 A4

B

我的来源地址是:E:\ A \ A2

我的目的地地址是E:\ B

我想在B中复制A2,其中A2为空。

如果我使用代码

 public  void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);
        string vSourceDirName = dir.Name;
        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }

        DirectoryInfo[] dirs = dir.GetDirectories();
        // If the destination directory doesn't exist, create it.
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }

        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string temppath = Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, false);
        }

        // If copying subdirectories, copy them and their contents to new location.
        if (copySubDirs)
        {
            foreach (DirectoryInfo subdir in dirs)
            {
                string temppath = Path.Combine(destDirName,vSourceDirName,subdir.Name);
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }

    }

本规范来自msdn 如何在C#中复制此空文件夹

  

块引用

1 个答案:

答案 0 :(得分:1)

您可以使用DirectoryCopy()函数。 使用您的示例尝试DirectoryCopy(@“E:\ A \ A2”,@“E:\ B”,true),您将获得E:\ B \ A2创建。