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

发布于 2024-07-05 14:47:19 字数 493 浏览 5 评论 0原文

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

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

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

应移动到:

C:\Program Files\Orca Tools\Wire Orca\Orcay 10\Orca。当然

,同样的操作也应该应用于每个文件夹级别中的每个子对象。

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

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

没用。

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最好是你 2024-07-12 14:47:19
string oldPath = "\\shark.exe"
string newPath = oldPath.Replace("shark", "orca");

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

填写你自己的完整路径

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

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

Fill in with your own full paths

≈。彩虹 2024-07-12 14:47:19

所以你会使用递归。 下面是一个 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"

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文