递归复制文件

发布于 2024-11-30 04:02:16 字数 1124 浏览 2 评论 0原文

我发现了一个用于在 C# 中进行递归文件复制的小片段,但我有些困惑。我基本上需要将目录结构复制到另一个位置,沿着这个...

源:C:\data\servers\mc

目标:E:\mc

目前我的复制功能的代码是...

    //Now Create all of the directories
    foreach (string dirPath in Directory.GetDirectories(baseDir, "*", SearchOption.AllDirectories))
    {
        Directory.CreateDirectory(dirPath.Replace(baseDir, targetDir));
    }


    // Copy each file into it’s new directory.
    foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
    {
        Console.WriteLine(@"Copying {0}\{1}", targetDir, Path.GetFileName(file));
        if (!CopyFile(file, Path.Combine(targetDir, Path.GetFileName(file)), false))
        {
            int err = Marshal.GetLastWin32Error();
            Console.WriteLine("[ERROR] CopyFile Failed on {0} with code {1}", file, err);
        }
    }

问题是,在第二个范围中,我要么:

  1. 使用 Path.GetFileName(file) 获取不带路径的实际文件名,但我丢失了目录“mc”目录结构或< /strong>
  2. 使用“文件”而不使用 Path.Combine。

无论哪种方式,我都必须做一些令人讨厌的字符串工作。在 C# 中是否有一个好的方法来做到这一点(我对 .NET API 缺乏了解导致我把事情变得过于复杂)

I found a small snippet for doing a recursive file copy in C#, but am somewhat stumped. I basically need to copy a directory structure to another location, along the lines of this...

Source: C:\data\servers\mc

Target: E:\mc

The code for my copy function as of right now is...

    //Now Create all of the directories
    foreach (string dirPath in Directory.GetDirectories(baseDir, "*", SearchOption.AllDirectories))
    {
        Directory.CreateDirectory(dirPath.Replace(baseDir, targetDir));
    }


    // Copy each file into it’s new directory.
    foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
    {
        Console.WriteLine(@"Copying {0}\{1}", targetDir, Path.GetFileName(file));
        if (!CopyFile(file, Path.Combine(targetDir, Path.GetFileName(file)), false))
        {
            int err = Marshal.GetLastWin32Error();
            Console.WriteLine("[ERROR] CopyFile Failed on {0} with code {1}", file, err);
        }
    }

The issue is that in the second scope, I either:

  1. use Path.GetFileName(file) to get the actual file name without the path but I lose the directory "mc" directory structure or
  2. use "file" without Path.Combine.

Either way I have to do some nasty string work. Is there a good way to do this in C# (my lack of knowledge with the .NET API leads me to over complicating things)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

月依秋水 2024-12-07 04:02:16

MSDN 有一个完整的示例:如何:复制目录

using System;
using System.IO;

class DirectoryCopyExample
{
    static void Main()
    {
        // Copy from the current directory, include subdirectories.
        DirectoryCopy(".", @".\temp", true);
    }

    private static void DirectoryCopy(string sourceDirName, string destDirName, 
                                      bool copySubDirs)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);

        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }

        DirectoryInfo[] dirs = dir.GetDirectories();
        // If the destination directory doesn't exist, create it.
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }

        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string temppath = Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, false);
        }

        // If copying subdirectories, copy them and their contents to new location.
        if (copySubDirs)
        {
            foreach (DirectoryInfo subdir in dirs)
            {
                string temppath = Path.Combine(destDirName, subdir.Name);
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }
    }
}

MSDN has a complete sample: How to: copy directories

using System;
using System.IO;

class DirectoryCopyExample
{
    static void Main()
    {
        // Copy from the current directory, include subdirectories.
        DirectoryCopy(".", @".\temp", true);
    }

    private static void DirectoryCopy(string sourceDirName, string destDirName, 
                                      bool copySubDirs)
    {
        // Get the subdirectories for the specified directory.
        DirectoryInfo dir = new DirectoryInfo(sourceDirName);

        if (!dir.Exists)
        {
            throw new DirectoryNotFoundException(
                "Source directory does not exist or could not be found: "
                + sourceDirName);
        }

        DirectoryInfo[] dirs = dir.GetDirectories();
        // If the destination directory doesn't exist, create it.
        if (!Directory.Exists(destDirName))
        {
            Directory.CreateDirectory(destDirName);
        }

        // Get the files in the directory and copy them to the new location.
        FileInfo[] files = dir.GetFiles();
        foreach (FileInfo file in files)
        {
            string temppath = Path.Combine(destDirName, file.Name);
            file.CopyTo(temppath, false);
        }

        // If copying subdirectories, copy them and their contents to new location.
        if (copySubDirs)
        {
            foreach (DirectoryInfo subdir in dirs)
            {
                string temppath = Path.Combine(destDirName, subdir.Name);
                DirectoryCopy(subdir.FullName, temppath, copySubDirs);
            }
        }
    }
}
゛时过境迁 2024-12-07 04:02:16

答案的非递归替换是:

private static void DirectoryCopy(string sourceBasePath, string destinationBasePath, bool recursive = true)
{
    if (!Directory.Exists(sourceBasePath))
        throw new DirectoryNotFoundException($"Directory '{sourceBasePath}' not found");

    var directoriesToProcess = new Queue<(string sourcePath, string destinationPath)>();
    directoriesToProcess.Enqueue((sourcePath: sourceBasePath, destinationPath: destinationBasePath));
    while (directoriesToProcess.Any())
    {
        (string sourcePath, string destinationPath) = directoriesToProcess.Dequeue();

        if (!Directory.Exists(destinationPath))
            Directory.CreateDirectory(destinationPath);

        var sourceDirectoryInfo = new DirectoryInfo(sourcePath);
        foreach (FileInfo sourceFileInfo in sourceDirectoryInfo.EnumerateFiles())
            sourceFileInfo.CopyTo(Path.Combine(destinationPath, sourceFileInfo.Name), true);

        if (!recursive)
            continue;

        foreach (DirectoryInfo sourceSubDirectoryInfo in sourceDirectoryInfo.EnumerateDirectories())
            directoriesToProcess.Enqueue((
                sourcePath: sourceSubDirectoryInfo.FullName,
                destinationPath: Path.Combine(destinationPath, sourceSubDirectoryInfo.Name)));
    }
}

A non-recursive replacement for this answer would be:

private static void DirectoryCopy(string sourceBasePath, string destinationBasePath, bool recursive = true)
{
    if (!Directory.Exists(sourceBasePath))
        throw new DirectoryNotFoundException($"Directory '{sourceBasePath}' not found");

    var directoriesToProcess = new Queue<(string sourcePath, string destinationPath)>();
    directoriesToProcess.Enqueue((sourcePath: sourceBasePath, destinationPath: destinationBasePath));
    while (directoriesToProcess.Any())
    {
        (string sourcePath, string destinationPath) = directoriesToProcess.Dequeue();

        if (!Directory.Exists(destinationPath))
            Directory.CreateDirectory(destinationPath);

        var sourceDirectoryInfo = new DirectoryInfo(sourcePath);
        foreach (FileInfo sourceFileInfo in sourceDirectoryInfo.EnumerateFiles())
            sourceFileInfo.CopyTo(Path.Combine(destinationPath, sourceFileInfo.Name), true);

        if (!recursive)
            continue;

        foreach (DirectoryInfo sourceSubDirectoryInfo in sourceDirectoryInfo.EnumerateDirectories())
            directoriesToProcess.Enqueue((
                sourcePath: sourceSubDirectoryInfo.FullName,
                destinationPath: Path.Combine(destinationPath, sourceSubDirectoryInfo.Name)));
    }
}
甚是思念 2024-12-07 04:02:16

而不是

foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{

做这样的事情

foreach (FileInfo fi in source.GetFiles())
{
     fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}

instead of

foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{

do something like this

foreach (FileInfo fi in source.GetFiles())
{
     fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文