Search code examples
c#io

How Can I Copy Directory from Source to destination Even if Directory is Empty?


Follow This Structure.

A
 A1
   A111
 A2
 A3
 A4

B

My Source Address is: E:\A\A2

My Destination Address is E:\B

I want to Copy A2 in B where A2 is Empty.

If I use Code

 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);
            }
        }

    }

This Code is from msdn How Can I Copy this Empty Folder in C#

Blockquote


Solution

  • You could use the function DirectoryCopy(). Using your example try DirectoryCopy (@"E:\A\A2", @"E:\B", true) and you will get E:\B\A2 created.