【问题标题】:How to copy files from one disk to another location with the same folder structure?如何将文件从一个磁盘复制到具有相同文件夹结构的另一个位置?
【发布时间】:2012-09-13 00:35:50
【问题描述】:

我想对我的 USB 驱动器 I:/ 上的一些文件、目录和子目录进行精确复制,并希望它们位于 C:/backup(例如)

我的 U 盘结构如下:

(只是要知道,这是一个例子,我的驱动器有更多的文件、目录和子目录)

  • courses/data_structures/db.sql

  • games/pc/pc-game.exe

  • exams/exam01.doc


好吧,我不知道如何开始,但我的第一个想法是让所有files 这样做:

string[] files = Directory.GetFiles("I:");

下一步可能是创建一个循环并使用File.Copy 指定目标路径:

string destinationPath = @"C:/backup";

foreach (string file in files)
{
  File.Copy(file, destinationPath + "\\" + Path.GetFileName(file), true);
}

此时一切正常,但不是我想要的,因为这不会复制文件夹结构。还会发生一些错误,如下所示...

  • 第一个发生是因为我的 PC 配置显示每个文件夹的隐藏文件,而我的 USB 有一个不再隐藏的 AUTORUN.INF 隐藏文件,循环尝试复制它,并在此过程中生成此异常:

对路径“AUTORUN.INF”的访问被拒绝。

  • 当某些路径太长时会发生第二个异常,这会产生以下异常:

指定的路径、文件名或两者都太长。完全 限定文件名必须少于 260 个字符,并且 目录名称必须少于 248 个字符。


所以,我不确定如何实现这一点并验证每个可能的错误情况。我想知道是否有另一种方法可以做到这一点以及如何(可能是某个库)或更简单的方法,例如具有以下结构的已实现方法:

File.CopyDrive(driveLetter, destinationFolder)

(VB.NET 的答案也将被接受)。

提前致谢。

【问题讨论】:

    标签: c# vb.net file copy .net


    【解决方案1】:
    public static void Copy(string src, string dest)
    {
        // copy all files
        foreach (string file in Directory.GetFiles(src))
        {
            try
            {
                File.Copy(file, Path.Combine(dest, Path.GetFileName(file)));
            }
            catch (PathTooLongException)
            {
            }
            // catch any other exception that you want.
            // List of possible exceptions here: http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx
        }
    
        // go recursive on directories
        foreach (string dir in Directory.GetDirectories(src))
        {
    
            // First create directory...
            // Instead of new DirectoryInfo(dir).Name, you can use any other way to get the dir name,
            // but not Path.GetDirectoryName, since it returns full dir name.
            string destSubDir = Path.Combine(dest, new DirectoryInfo(dir).Name);
            Directory.CreateDirectory(destSubDir);
            // and then go recursive
            Copy(dir, destSubDir);
        }
    }
    

    然后你就可以调用它了:

    Copy(@"I:\", @"C:\Backup");
    

    没有时间测试它,但我希望你能明白...

    编辑:在上面的代码中,没有像 Directory.Exists 之类的检查,如果目标路径中存在某种目录结构,您可以添加这些检查。如果您正在尝试创建某种简单的同步应用程序,那么它会变得有点困难,因为您需要删除或对不再存在的文件/文件夹采取其他操作。

    【讨论】:

      【解决方案2】:

      这通常从递归下降解析器开始。这是一个很好的例子:http://msdn.microsoft.com/en-us/library/bb762914.aspx

      【讨论】:

        【解决方案3】:

        您可能想查看重载的CopyDirectory

        CopyDirectory(String, String, UIOption, UICancelOption)
        

        它将遍历所有子目录。

        如果你想要一个独立的应用程序,我已经编写了一个应用程序,它可以从一个选定的目录复制到另一个目录,覆盖较新的文件并根据需要添加子目录。

        给我发电子邮件。

        【讨论】:

          猜你喜欢
          • 2011-05-03
          • 1970-01-01
          • 1970-01-01
          • 2021-12-18
          • 2019-09-15
          • 1970-01-01
          • 1970-01-01
          • 2013-05-02
          相关资源
          最近更新 更多