views:

438

answers:

3

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 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 "genious" way to perfom this kind of operation.

Klaus

+1  A: 

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
A: 
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
A: 

Great stuff EBGreen,

I was actually looking for a PowerShell solution.

Right on!

Klaus