Recursively copy directory contents in C#
Copying the contents of an entire directory is a common task in software development. While there doesn't seem to be a direct way to achieve this in System.IO, alternatives exist.
A workaround is to use the Microsoft.VisualBasic.Devices.Computer class, which can be accessed by adding a reference to Microsoft.VisualBasic:
<code class="language-csharp">new Microsoft.VisualBasic.Devices.Computer(). FileSystem.CopyDirectory(sourceFolder, outputFolder);</code>
However, this approach is not considered an elegant solution. A more robust approach involves the following steps:
The following code demonstrates this approach:
<code class="language-csharp">private static void CopyFilesRecursively(string sourcePath, string targetPath) { // 在目标路径中创建目录 foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)); } // 将文件从源路径复制到目标路径 foreach (string newPath in Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); } }</code>
This method recursively copies the entire source directory (including subdirectories and files) to the specified target directory. It also replaces any existing files with the same name.
The above is the detailed content of How to Recursively Copy a Directory's Contents in C#?. For more information, please follow other related articles on the PHP Chinese website!