copy a directory in csharp

You can use the System.IO namespace to copy a directory in C#. You can use the Directory class to manipulate directories. To copy a directory, you can use the Directory.CopyTo method. Here's a code snippet that demonstrates how to copy a directory:

main.cs
string sourceDirPath = @"C:\source_directory";
string destDirPath = @"C:\destination_directory";

if (!Directory.Exists(destDirPath))
{
    Directory.CreateDirectory(destDirPath);
}

foreach (string file in Directory.GetFiles(sourceDirPath))
{
    string destFile = Path.Combine(destDirPath, Path.GetFileName(file));
    File.Copy(file, destFile, true);
}

foreach (string directory in Directory.GetDirectories(sourceDirPath))
{
    string destDir = Path.Combine(destDirPath, Path.GetFileName(directory));
    DirectoryCopy(directory, destDir);
}
547 chars
20 lines

In the code, we first define the paths for the source and destination directories. We then check if the destination directory exists, and if not, create it using Directory.CreateDirectory. We then loop through all the files in the source directory and use File.Copy to copy each file to the destination directory. Finally, we loop through all the subdirectories in the source directory and recursively call DirectoryCopy to copy each subdirectory to the destination directory.

Note that this implementation does not handle errors such as file access exceptions, so you may want to add additional error handling code to your application.

gistlibby LogSnag