Home >Backend Development >C++ >How to Recursively Copy a Directory's Contents in C#?

How to Recursively Copy a Directory's Contents in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-26 19:51:09417browse

How to Recursively Copy a Directory's Contents in C#?

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:

  1. Create all necessary directories in the target path to match the structure of the source directory.
  2. Copies each file from the source path to the corresponding destination path, overwriting any existing files with the same name.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn