当前位置: 动力学知识库 > 问答 > 编程问答 >

replace names of all directiories and files in C#

问题描述:

This question had asked for PowerShell before. I want to do this in C#.

I have a directory on my desktop. The directories name is "rename".

C:\Users\dell\Desktop\rename

And "rename" folder contains "a_b", "b_c", "c_d", "d_e" folders.

I want to replace "_" with "-" characters.

In other words, folders' new names will be "a-b", "b-c", "c-d", "d-e"

Thank you for your help!

网友答案:

Create a DirectoryInfo object representing the rename folder, iterate through its subfolders, and use String.Replace to replace _ with -:

DirectoryInfo parent = new DirectoryInfo(@"C:\Users\dell\Desktop\rename");

foreach(DirectoryInfo child in parent.GetDirectories()) {
    string newName = child.FullPath.Replace('_', '-');

    if(newName != child.FullPath) {
        child.MoveTo(newName);
    }
}
网友答案:

"Rename" files like this:

http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/435a2692-6161-4039-bfa9-5e6211d90c49/

And you can do filename.Replace('_', '-') on each filename to replace underscores with hyphens.

分享给朋友:
您可能感兴趣的文章:
随机阅读: