使用 System.IO 在 C# 中复制文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/677221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:04:24  来源:igfitidea点击:

Copy Folders in C# using System.IO

c#asp.netfile-io.net

提问by Etienne

I need to Copy folder C:\FromFolder to C:\ToFolder

我需要将文件夹 C:\FromFolder 复制到 C:\ToFolder

Below is code that will CUT my FromFolder and then will create my ToFolder. So my FromFolder will be gone and all the items will be in the newly created folder called ToFolder

下面是将剪切我的 FromFolder 然后将创建我的 ToFolder 的代码。所以我的 FromFolder 将消失,所有项目都将在新创建的名为 ToFolder 的文件夹中

System.IO.Directory.Move(@"C:\FromFolder ", @"C:\ToFolder");

But i just want to Copy the files in FromFolder to ToFolder. For some reason there is no System.IO.Directory.Copy???

但我只想将 FromFolder 中的文件复制到 ToFolder。出于某种原因,没有 System.IO.Directory.Copy ???

How this is done using a batch file - Very easy

这是如何使用批处理文件完成的 - 非常简单

xcopy C:\FromFolder C:\ToFolder

xcopy C:\FromFolder C:\ToFolder

Regards Etienne

问候艾蒂安

采纳答案by bendewey

This link provides a nice example.

这个链接提供了一个很好的例子。

http://msdn.microsoft.com/en-us/library/cc148994.aspx

http://msdn.microsoft.com/en-us/library/cc148994.aspx

Here is a snippet

这是一个片段

// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
//       in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
  string[] files = System.IO.Directory.GetFiles(sourcePath);

  // Copy the files and overwrite destination files if they already exist.
  foreach (string s in files)
  {
    // Use static Path methods to extract only the file name from the path.
    fileName = System.IO.Path.GetFileName(s);
    destFile = System.IO.Path.Combine(targetPath, fileName);
    System.IO.File.Copy(s, destFile, true);
  }
}

回答by RvdK

there is a file copy. Recreate folder and copy all the files from original directory to the new one example

有一个文件副本。重新创建文件夹并将所有文件从原始目录复制到新的一个 示例

static void Main(string[] args)
    {
        DirectoryInfo sourceDir = new DirectoryInfo("c:\a");
        DirectoryInfo destinationDir = new DirectoryInfo("c:\b");

        CopyDirectory(sourceDir, destinationDir);

    }

    static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
    {
        if (!destination.Exists)
        {
            destination.Create();
        }

        // Copy all files.
        FileInfo[] files = source.GetFiles();
        foreach (FileInfo file in files)
        {
            file.CopyTo(Path.Combine(destination.FullName, 
                file.Name));
        }

        // Process subdirectories.
        DirectoryInfo[] dirs = source.GetDirectories();
        foreach (DirectoryInfo dir in dirs)
        {
            // Get destination directory.
            string destinationDir = Path.Combine(destination.FullName, dir.Name);

            // Call CopyDirectory() recursively.
            CopyDirectory(dir, new DirectoryInfo(destinationDir));
        }
    }

回答by Ian Jacobs

You'll need to create a new directory from scratch then loop through all the files in the source directory and copy them over.

您需要从头开始创建一个新目录,然后遍历源目录中的所有文件并复制它们。

string[] files = Directory.GetFiles(GlobalVariables.mstrReadsWellinPath);
foreach(string s in files)
{
        fileName=Path.GetFileName(s);
        destFile = Path.Combine(DestinationPath, fileName);
        File.Copy(s, destFile);
}

I leave creating the destination directory to you :-)

我将创建目标目录留给您:-)

回答by Philippe

This article provides an alogirthm to copy recursively some folder and all its content

本文提供了一种递归复制某个文件夹及其所有内容的算法

From the article :

从文章:

Sadly there is no built-in function in System.IO that will copy a folder and its contents. Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the destination folder if needed. For simplicity, there is no error handling; an exception will throw if anything goes wrong, such as null or invalid paths or if the destination files already exist.

遗憾的是,System.IO 中没有内置函数可以复制文件夹及其内容。以下是一个简单的递归算法,用于复制文件夹、其子文件夹和文件,并在需要时创建目标文件夹。为简单起见,没有错误处理;如果出现任何错误,例如 null 或无效路径,或者目标文件已存在,则会引发异常。

Good luck!

祝你好运!

回答by Jonathan van de Veen

You're right. There is no Directory.Copy method. It would be a very powerful method, but also a dangerous one, for the unsuspecting developer. Copying a folder can potentionaly be a very time consuming operation, while moving one (on the same drive) is not.

你是对的。没有 Directory.Copy 方法。对于毫无戒心的开发人员来说,这将是一种非常强大的方法,但也是一种危险的方法。复制文件夹可能是一项非常耗时的操作,而移动文件夹(在同一驱动器上)则不然。

I guess Microsoft thought it would make sence to copy file by file, so you can then show some kind of progress information. You could iterate trough the files in a directory by creating an instance of DirectoryInfo and then calling GetFiles(). To also include subdirectories you can also call GetDirectories() and enumerate trough these with a recursive method.

我猜微软认为逐个文件复制是有意义的,这样你就可以显示某种进度信息。您可以通过创建 DirectoryInfo 的实例然后调用 GetFiles() 来遍历目录中的文件。要还包含子目录,您还可以调用 GetDirectories() 并使用递归方法枚举这些子目录。

回答by lakshmanaraj

回答by lakshmanaraj

Copying directories (correctly) is actually a rather complex task especially if you take into account advanced filesystem techniques like junctions and hard links. Your best bet is to use an API that supports it. If you aren't afraid of a little P/Invoke, SHFileOperation in shell32 is your best bet. Another alternative would be to use the Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory method in the Microsoft.VisualBasic assembly (even if you aren't using VB).

复制目录(正确)实际上是一项相当复杂的任务,特别是如果您考虑到诸如联结和硬链接之类的高级文件系统技术。最好的办法是使用支持它的 API。如果你不怕一点 P/Invoke,shell32 中的 SHFileOperation 是你最好的选择。另一种替代方法是在 Microsoft.VisualBasic 程序集中使用 Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory 方法(即使您没有使用 VB)。

回答by diegodsp

My version of DirectoryInfo.CopyTo using extension.

我使用扩展名的 DirectoryInfo.CopyTo 版本。

public static class DirectoryInfoEx {
    public static void CopyTo(this DirectoryInfo source, DirectoryInfo target) {
        if (source.FullName.ToLower() == target.FullName.ToLower())
            return;

        if (!target.Exists)
            target.Create();

        foreach (FileInfo f in source.GetFiles()) {
            FileInfo newFile = new FileInfo(Path.Combine(target.FullName, f.Name));
            f.CopyTo(newFile.FullName, true);
        }

        foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
            DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
            diSourceSubDir.CopyTo(nextTargetSubDir);
        }
    }
}

And use like that...

并像那样使用...

DirectoryInfo d = new DirectoryInfo("C:\Docs");
d.CopyTo(new DirectoryInfo("C:\New"));

回答by Ramil Shavaleev

A simple function that copies the entire contents of the source folder to the destination folder and creates the destination folder if it doesn't exist

一个简单的函数,将源文件夹的全部内容复制到目标文件夹,如果目标文件夹不存在则创建目标文件夹

class Utils
{
    internal static void copy_dir(string source, string dest)
    {
        if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(dest)) return;
        Directory.CreateDirectory(dest);
        foreach (string fn in Directory.GetFiles(source))
        {
            File.Copy(fn, Path.Combine(dest, Path.GetFileName(fn)), true);
        }
        foreach (string dir_fn in Directory.GetDirectories(source))
        {
            copy_dir(dir_fn, Path.Combine(dest, Path.GetFileName(dir_fn)));
        }
    }
}