0

I would like to rename files and folders recursively by applying a string replacement operation.

E.g. The word "shark" in files and folders should be replaced by the word "orca".

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

should be moved to:

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

The same operation should be of course applied to each child object in each folder level as well.

I was experimenting with some of the members of the System.IO.FileInfo and System.IO.DirectoryInfo classes but didn't find an easy way to do it.

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

Doesn't do the trick.

I was hoping there is some kind of "genius" way to perform this kind of operation. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

4

2 回答 2

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"
于 2008-08-19T21:46:09.693 回答
0
string oldPath = "\\shark.exe"
string newPath = oldPath.Replace("shark", "orca");

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

填写您自己的完整路径

于 2008-08-19T22:00:15.903 回答