copy a directory in csharp in csharp

To copy a directory in C#, you can use the System.IO namespace which contains the Directory class to perform file and directory operations. Here's an example code snippet to copy a directory in C#:

main.cs
using System.IO;

public static void CopyDirectory(string sourceDir, string destinationDir)
{
    DirectoryInfo dir = new DirectoryInfo(sourceDir);

    // If the source directory does not exist, throw an exception
    if (!dir.Exists)
    {
        throw new DirectoryNotFoundException(
            "Source directory does not exist or could not be found: " 
            + sourceDir);
    }

    // If the destination directory does not exist, create it.
    if (!Directory.Exists(destinationDir))
    {
        Directory.CreateDirectory(destinationDir);
    }

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

    // Get the subdirectories in the source directory and copy them to the destination directory
    DirectoryInfo[] dirs = dir.GetDirectories();
    foreach (DirectoryInfo subdir in dirs)
    {
        string temppath = Path.Combine(destinationDir, subdir.Name);
        CopyDirectory(subdir.FullName, temppath);
    }
}
1175 chars
37 lines

This method recursively copies all files and directories from the source directory to the destination directory. It checks if the directories exist, creates them if they don't, and then copies the files and directories to the destination directory.

related categories

gistlibby LogSnag