在C#中復制目錄的全部內容 (Copy the entire contents of a directory in C#)


問題描述

在 C# 中復制目錄的全部內容 (Copy the entire contents of a directory in C#)

我想在 C# 中將目錄的全部內容從一個位置複製到另一個位置。

似乎沒有辦法使用 System.IO 沒有大量遞歸的類。

如果我們添加對 Microsoft.VisualBasic 的引用,我們可以使用 VB 中的一種方法:

new Microsoft.VisualBasic.Devices.Computer().
    FileSystem.CopyDirectory( sourceFolder, outputFolder );

這似乎是一個相當醜陋的黑客。有沒有更好的辦法?


參考解法

方法 1:

Much easier

private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
    //Now Create all of the directories
    foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
    {
        Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
    }

    //Copy all the files & Replaces any files with the same name
    foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))
    {
        File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
    }
}

方法 2:

Hmm, I think I misunderstand the question but I'm going to risk it. What's wrong with the following straightforward method?

public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) {
    foreach (DirectoryInfo dir in source.GetDirectories())
        CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
    foreach (FileInfo file in source.GetFiles())
        file.CopyTo(Path.Combine(target.FullName, file.Name));
}

EDIT Since this posting has garnered an impressive number of downvotes for such a simple answer to an equally simple question, let me add an explanation. Please read this before downvoting.

First of all, this code is not intendend as a drop‑in replacement to the code in the question. It is for illustration purpose only.

Microsoft.VisualBasic.Devices.Computer.FileSystem.CopyDirectory does some additional correctness tests (e.g. whether the source and target are valid directories, whether the source is a parent of the target etc.) that are missing from this answer. That code is probably also more optimized.

That said, the code works well. It has (almost identically) been used in a mature software for years. Apart from the inherent fickleness present with all IO handlings (e.g. what happens if the user manually unplugs the USB drive while your code is writing to it?), there are no known problems.

In particular, I’d like to point out that the use of recursion here is absolutely not a problem. Neither in theory (conceptually, it’s the most elegant solution) nor in practice: this code will not overflow the stack. The stack is large enough to handle even deeply nested file hierarchies. Long before stack space becomes a problem, the folder path length limitation kicks in.

Notice that a malicious user might be able to break this assumption by using deeply‑nested directories of one letter each. I haven’t tried this. But just to illustrate the point: in order to make this code overflow on a typical computer, the directories would have to be nested a few thousand times. This is simply not a realistic scenario.

方法 3:

Copied from MSDN:

using System;
using System.IO;

class CopyDir
{
    public static void Copy(string sourceDirectory, string targetDirectory)
    {
        DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
        DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);

        CopyAll(diSource, diTarget);
    }

    public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
    {
        Directory.CreateDirectory(target.FullName);

        // Copy each file into the new directory.
        foreach (FileInfo fi in source.GetFiles())
        {
            Console.WriteLine(@"Copying {0}\{1}", target.FullName, fi.Name);
            fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);
        }

        // Copy each subdirectory using recursion.
        foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
        {
            DirectoryInfo nextTargetSubDir =
                target.CreateSubdirectory(diSourceSubDir.Name);
            CopyAll(diSourceSubDir, nextTargetSubDir);
        }
    }

    public static void Main()
    {
        string sourceDirectory = @"c:\sourceDirectory";
        string targetDirectory = @"c:\targetDirectory";

        Copy(sourceDirectory, targetDirectory);
    }

    // Output will vary based on the contents of the source directory.
}

方法 4:

Or, if you want to go the hard way, add a reference to your project for Microsoft.VisualBasic and then use the following:

Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(fromDirectory, toDirectory);

However, using one of the recursive functions is a better way to go since it won't have to load the VB dll.

方法 5:

Try this:

Process proc = new Process();
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "xcopy.exe");
proc.StartInfo.Arguments = @"C:\source C:\destination /E /I";
proc.Start();

Your xcopy arguments may vary but you get the idea.

(by KeithtboswellKonrad RudolphJustin R.Josefd4nt)

參考文件

  1. Copy the entire contents of a directory in C# (CC BY‑SA 2.5/3.0/4.0)

#directory #.net #copy #C#






相關問題

區分 C 和 C++ 中的 unix 目錄和文件 (Differentiate between a unix directory and file in C and C++)

如何將空白目錄添加到 Git 存儲庫? (How can I add a blank directory to a Git repository?)

Cách xóa mọi thứ trong thư mục bằng C # (How to delete everything in a folder with C#)

Tại sao tôi không thể chuyển một thư mục làm đối số cho vòng lặp for trong bash? (Why can't I pass a directory as an argument to a for loop in bash?)

為什麼 `Dir[directory_path].empty?` 總是返回 `false`? (Why does `Dir[directory_path].empty?` return `false` all the time?)

html目錄路徑中變量的語法 (Syntax for variables in html directory path)

打開文件夾中的所有 .csv 並返回新的輸出 (Open all .csv in a folder and return a new output)

沒有 .htaccess 的安全目錄密碼保護 (Secure directory password protection without .htaccess)

如何獲取 Eclipse 安裝目錄的絕對路徑? (How can I get the absolute path to the Eclipse install directory?)

獲取調用 Python 腳本的快捷方式的目錄 (Get the directory of a Shortcut calling a Python Script)

如何將一堆同名文件複製到一個文件夾中? (How to copy a bunch of files with same name to a folder?)

在python中將基目錄更改為上層目錄 (Change base directory to upper directory in python)







留言討論