在.NET中重命名(移动)文件系统分支的最佳方法是什么?

时间:2020-03-05 18:40:53  来源:igfitidea点击:

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

例如。文件和文件夹中的" shark"一词应替换为" orca"一词。

C:\ Program Files \ Shark工具\ Wire Shark \ Sharky 10 \ Shark.exe

应移至:

C:\ Program Files \ Orca工具\ Wire Orca \ Orcay 10 \ Orca.exe

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

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

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

不能解决问题。

我希望有某种"天才"方法来执行这种操作。

解决方案

回答

因此,我们将使用递归。这是一个易于转换为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"

回答

string oldPath = "\shark.exe"
string newPath = oldPath.Replace("shark", "orca");

System.IO.File.Move(oldPath, newPath);

填写自己的完整路径