【问题标题】:Copying files and subdirectories to another directory with existing files将文件和子目录复制到具有现有文件的另一个目录
【发布时间】:2013-09-30 12:54:51
【问题描述】:

我在这个问题上卡住了一段时间。我需要复制(更新)从 Folder1\directory1 到 Updated\directory1 的所有内容,覆盖相同的文件,但不删除已在 Updated\directory1 上存在但在 Folder1\directory1 上不存在的文件。为了让我的问题更清楚,这是我的预期结果:

C:\Folder1\directory1

子文件夹1

subtext1.txt (2KB)

子文件夹2

name.txt (2KB)

C:\Updated\directory1

子文件夹1

subtext1.txt (1KB)

subtext2.txt (2KB)

预期结果:

C:\Updated\directory1

子文件夹1

subtext1.txt (2KB)

subtext2.txt (2KB)

子文件夹2

name.txt (2KB)

我目前正在使用Directory.Move(source, destination),但我在目标部分遇到问题,因为其中一些目标文件夹不存在。我唯一的想法是使用String.Trim 来确定是否还有其他文件夹,但我不能真正使用它,因为目录应该是动态的(可以有更多子目录或更多文件夹)。我真的被困住了。你能推荐一些提示或一些代码来让我的东西移动吗?谢谢!

【问题讨论】:

    标签: c# copy directory


    【解决方案1】:

    我从 msdn http://msdn.microsoft.com/en-us/library/cc148994.aspx 得到了这个例子,我想这就是你要找的

    // 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);
            }
        }
        else
        {
            Console.WriteLine("Source path does not exist!");
        }
    

    如果您需要处理不存在的文件夹路径,您应该创建一个新文件夹

    if (System.IO.Directory.Exists(targetPath){
        System.IO.Directory.CreateDirectory(targetPath);
    }
    

    【讨论】:

      【解决方案2】:

      将所有文件从文件夹并行快速复制到具有任何嵌套级别的文件夹

      在复制 100,000 个文件时进行了测试

      using System.IO;
      using System.Linq;
      
      namespace Utilities
      {
          public static class DirectoryUtilities
          {
              public static void Copy(string fromFolder, string toFolder, bool overwrite = false)
              {
                  Directory
                      .EnumerateFiles(fromFolder, "*.*", SearchOption.AllDirectories)
                      .AsParallel()
                      .ForAll(from =>
                      {
                          var to = from.Replace(fromFolder, toFolder);
      
                          // Create directories if required
                          var toSubFolder = Path.GetDirectoryName(to);
                          if (!string.IsNullOrWhiteSpace(toSubFolder))
                          {
                              Directory.CreateDirectory(toSubFolder);
                          }
      
                          File.Copy(from, to, overwrite);
                      });
              }
          }
      }
      

      【讨论】:

        【解决方案3】:
        // This can be handled any way you want, I prefer constants
        const string STABLE_FOLDER = @"C:\temp\stable\";
        const string UPDATE_FOLDER = @"C:\temp\updated\";
        
        // Get our files (recursive and any of them, based on the 2nd param of the Directory.GetFiles() method
        string[] originalFiles = Directory.GetFiles(STABLE_FOLDER,"*", SearchOption.AllDirectories);
        
        // Dealing with a string array, so let's use the actionable Array.ForEach() with a anonymous method
        Array.ForEach(originalFiles, (originalFileLocation) => 
        {       
            // Get the FileInfo for both of our files
            FileInfo originalFile = new FileInfo(originalFileLocation);
            FileInfo destFile = new FileInfo(originalFileLocation.Replace(STABLE_FOLDER, UPDATE_FOLDER)); 
                                            // ^^ We can fill the FileInfo() constructor with files that don't exist...
        
            // ... because we check it here
            if (destFile.Exists)
            {
                // Logic for files that exist applied here; if the original is larger, replace the updated files...
                if (originalFile.Length > destFile.Length)
                {
                    originalFile.CopyTo(destFile.FullName, true);
                }
            }       
            else // ... otherwise create any missing directories and copy the folder over
            {
                Directory.CreateDirectory(destFile.DirectoryName); // Does nothing on directories that already exist
                originalFile.CopyTo(destFile.FullName,false); // Copy but don't over-write  
            }
        
        });
        

        这是一个快速的一次性...这里没有实施错误处理。

        【讨论】:

        • 我知道这篇文章和回复是 6 岁,但我对您上面的示例有疑问。如何将源和目标引用放在 App.Config 文件中而不是在此页面上?
        • 没关系,我想通了。只需将“const string”行更改为此。 "string Src_FOLDER = ConfigurationManager.AppSettings["SrcFolder"]; string Dest_FOLDER = ConfigurationManager.AppSettings["DestFolder"]; 并将目的地放在“App.Config”页面中。谢谢。
        【解决方案4】:

        这将帮助您它是一个通用递归函数,因此也总是合并子文件夹。

            /// <summary>
            /// Directories the copy.
            /// </summary>
            /// <param name="sourceDirPath">The source dir path.</param>
            /// <param name="destDirName">Name of the destination dir.</param>
            /// <param name="isCopySubDirs">if set to <c>true</c> [is copy sub directories].</param>
            /// <returns></returns>
            public static void DirectoryCopy(string sourceDirPath, string destDirName, bool isCopySubDirs)
            {
                // Get the subdirectories for the specified directory.
                DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirPath);
                DirectoryInfo[] directories = directoryInfo.GetDirectories();
                if (!directoryInfo.Exists)
                {
                    throw new DirectoryNotFoundException("Source directory does not exist or could not be found: "
                        + sourceDirPath);
                }
                DirectoryInfo parentDirectory = Directory.GetParent(directoryInfo.FullName);
                destDirName = System.IO.Path.Combine(parentDirectory.FullName, destDirName);
        
                // 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 = directoryInfo.GetFiles();
        
                foreach (FileInfo file in files)
                {
                    string tempPath = System.IO.Path.Combine(destDirName, file.Name);
        
                    if (File.Exists(tempPath))
                    {
                        File.Delete(tempPath);
                    }
        
                    file.CopyTo(tempPath, false);
                }
                // If copying subdirectories, copy them and their contents to new location using recursive  function. 
                if (isCopySubDirs)
                {
                    foreach (DirectoryInfo item in directories)
                    {
                        string tempPath = System.IO.Path.Combine(destDirName, item.Name);
                        DirectoryCopy(item.FullName, tempPath, isCopySubDirs);
                    }
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-11-18
          • 2020-12-08
          • 2012-02-15
          • 1970-01-01
          • 1970-01-01
          • 2012-03-04
          相关资源
          最近更新 更多