Updated on Kisan Patel
This tutorial will show you how to copy a directory in C# .NET.
Here is the method to copy a directory using C#.
static void CopyDir(DirectoryInfo src, DirectoryInfo target) { if (!target.Exists) { target.Create(); FileInfo[] files = src.GetFiles(); foreach (FileInfo file in files) { file.CopyTo(Path.Combine(target.FullName, file.Name)); } DirectoryInfo[] dirs = src.GetDirectories(); foreach (DirectoryInfo dir in dirs) { string destinationDir = Path.Combine(target.FullName, dir.Name); CopyDir(dir, new DirectoryInfo(destinationDir)); } } }
In this method, we have use GetDirectories
method that returns the sub-directories of the current directory. GetFiles
method retrieves a file list from the current directory. You could use above method as shown in below code:
DirectoryInfo source = new DirectoryInfo(src_path); DirectoryInfo target = new DirectoryInfo(target_path); CopyDir(source, target);