【问题标题】:What is the best way to rename (move) file system branches in .NET?在 .NET 中重命名(移动)文件系统分支的最佳方法是什么?
【发布时间】:2010-09-06 05:27:07
【问题描述】:

我想通过应用字符串替换操作递归地重命名文件和文件夹。

例如文件和文件夹中的“shark”应替换为“orca”。

C:\Program Files\Shark Tools\Wire Shark\Sharky 10\Shark.exe

应移至:

C:\Program Files\Orca Tools\Wire Orca\Orcay 10\Orca.exe

同样的操作当然也应该应用于每个文件夹级别中的每个子对象。

我正在尝试使用 System.IO.FileInfoSystem.IO.DirectoryInfo 类的一些成员,但没有找到简单的方法。

fi.MoveTo(fi.FullName.Replace("shark", "orca"));

没用。

我希望有某种“天才”方式来执行这种操作。

【问题讨论】:

    标签: file directory system.io.fileinfo


    【解决方案1】:

    所以你会使用递归。这是一个应该很容易转换为 C# 的 powershell 示例:

    function Move-Stuff($folder)
    {
        foreach($sub in [System.IO.Directory]::GetDirectories($folder))
          {
            Move-Stuff $sub
        }
        $new = $folder.Replace("Shark", "Orca")
        if(!(Test-Path($new)))
        {
            new-item -path $new -type directory
        }
        foreach($file in [System.IO.Directory]::GetFiles($folder))
        {
            $new = $file.Replace("Shark", "Orca")
            move-item $file $new
        }
    }
    
    Move-Stuff "C:\Temp\Test"
    

    【讨论】:

      【解决方案2】:
      string oldPath = "\\shark.exe"
      string newPath = oldPath.Replace("shark", "orca");
      
      System.IO.File.Move(oldPath, newPath);
      

      填写你自己的完整路径

      【讨论】:

        猜你喜欢
        • 2011-03-31
        • 1970-01-01
        • 1970-01-01
        • 2010-09-22
        • 1970-01-01
        • 2011-03-10
        • 1970-01-01
        • 2021-06-07
        • 2013-08-10
        相关资源
        最近更新 更多