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

时间:2008-08-19 21:00:38

标签: file directory system.io.fileinfo

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

E.g。文件和文件夹中的“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"));

不行。

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

2 个答案:

答案 0 :(得分:1)

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

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"

答案 1 :(得分:0)

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

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

填写您自己的完整路径

相关问题