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. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

You Nguyen
  • 9,961
  • 4
  • 26
  • 52

2 Answers2

1

So you would use recursion. Here is a powershell example that should be easy to convert to 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"
EBGreen
  • 36,735
  • 12
  • 65
  • 85
0
string oldPath = "\\shark.exe"
string newPath = oldPath.Replace("shark", "orca");

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

Fill in with your own full paths

John Sheehan
  • 77,456
  • 30
  • 160
  • 194