【问题标题】:The best way to move a directory with all its contents(files or folders) in C#?在 C# 中移动目录及其所有内容(文件或文件夹)的最佳方法?
【发布时间】:2014-04-11 06:49:24
【问题描述】:

在 C# 中移动目录及其所有内容(文件或文件夹)的最佳方法是什么?

我使用了以下代码,但它抛出了The Directory is not empty 异常:

Microsoft.VisualBasic.FileIO.FileSystem.MoveDirectory(sourceFullName, destFullName, true);
Directory.Move(sourceFullName, destFullName); //Added in edit

【问题讨论】:

标签: c# asp.net-mvc io


【解决方案1】:

MSDN 这个例子就足够了。

        string sourceDirectory = @"C:\source";
        string destinationDirectory = @"C:\destination";

        try
        {
            Directory.Move(sourceDirectory, destinationDirectory);  
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

即使如 MSDN 所说,如果出现以下情况,您也会收到 IOException:

  • 尝试将目录移动到不同的卷。

  • destDirName 已经存在。

  • sourceDirName 和 destDirName 参数引用同一个文件 或目录。

因此,请验证上述任何一项是否导致错误。

此外,您可以考虑在移动之前删除现有目录。如果错误是由于上面提到的第二个选项引起的,这将避免引发错误。

    if(Directory.Exists(destinationDirectory) == false)
    {
         Directory.Move(sourceDirectory, destinationDirectory);
    }
    else
    {
         //Delete existing directory
         //But make sure you really want to delete.
    }

【讨论】:

    【解决方案2】:

    你可以试试这个

        DirectoryInfo dir = new DirectoryInfo(source);
        dir.MoveTo(newLocation);
    

    【讨论】:

      【解决方案3】:

      使用 System.Io。

      string source = @"c:\new";
      string dest = @"c:\newnew";
      Directory.Move(source, dest);
      

      【讨论】:

        【解决方案4】:

        这里是一个例子......你应该在移动目录之前移动所有文件

         string fileName = "test.txt";
                string sourcePath = @"C:\Users\Public\TestFolder";
                string targetPath =  @"C:\Users\Public\TestFolder\SubDir";
        
                // Use Path class to manipulate file and directory paths. 
                string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
                string destFile = System.IO.Path.Combine(targetPath, fileName);
        
                // To copy a folder's contents to a new location: 
                // Create a new target folder, if necessary. 
                if (!System.IO.Directory.Exists(targetPath))
                {
                    System.IO.Directory.CreateDirectory(targetPath);
                }
        
                // To copy a file to another location and  
                // overwrite the destination file if it already exists.
                System.IO.File.Copy(sourceFile, destFile, true);
        
                // 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!");
                }
        

        【讨论】:

        • “你应该在移动目录之前移动所有文件”——一点也不。如果只需要将目录(及其整个子目录结构)移动到新位置,则上述答案是一种糟糕的方法。只需使用Directory.Move()DirectoryInfo.MoveTo()(正如其他答案所建议的那样)。
        【解决方案5】:

        使用它会帮助你:

                string sourceDir = @"c:\test";
                string destinationDir = @"c:\test1";
        
                try
                {
                    // Ensure the source directory exists
                    if (Directory.Exists(sourceDir) == true )
                    {
                        // Ensure the destination directory doesn't already exist
                        if (Directory.Exists(destinationDir) == false)
                        {
                            // Perform the move
                            Directory.Move(sourceDir, destinationDir);
                        }
                        else
                        {
                            // Could provide the user the option to delete the existing directory
                            // before moving the source directory
                        }
                    }
                    else
                    {
                        // Do something about the source directory not existing
                    }
                }
                catch (Exception)
                {
                    // TODO: Handle the exception that has been thrown
                }
        

        【讨论】:

          【解决方案6】:

          下面的解决方案怎么样,效果很好:

          public static void DeleteDirectory(string targetDir)
          {
              string[] files = Directory.GetFiles(targetDir, "*", SearchOption.AllDirectories);
              foreach (string file in files)
                  File.Delete(file);
              new Microsoft.VisualBasic.Devices.Computer().FileSystem.DeleteDirectory(targetDir, DeleteDirectoryOption.DeleteAllContents);
          }
          
          public static void MoveDirectory(string source, string dest)
          {
              new Microsoft.VisualBasic.Devices.Computer().FileSystem.CopyDirectory(source, dest, true);
              DeleteDirectory(source);
          }
          

          【讨论】:

            猜你喜欢
            • 2018-05-20
            • 2013-08-10
            • 2014-01-04
            • 2023-03-31
            • 1970-01-01
            • 2019-02-08
            • 2011-09-09
            • 2011-03-10
            • 1970-01-01
            相关资源
            最近更新 更多