0

I want to able to search through folders and subfolder names, then if they have a specific pattern on their name, change or remove them from the folder name. I used the below code but folderNameList return {}

string[] dirs = Directory.GetDirectories(myRootPath, "*", SearchOption.AllDirectories);


string findFolderNamePattern = @"((?i)mydomain.com|sitename(?-i))";
string replacement = " ";
Match folderNameList = Regex.Match(dirs.ToString(), findFolderNamePattern);

                foreach (var folder in folderNameList.ToString())
                {
                    folder = Regex.Replace(folder.ToString(), replacement);
                }

Also you can see the regex here

6
  • 3
    why are you ToStringing dirs? That won't give you what you want. Commented Aug 20, 2018 at 15:34
  • The same for folderNameList. Commented Aug 20, 2018 at 15:37
  • because it gets an error cannot convert from 'string[]' to 'string' Commented Aug 20, 2018 at 15:42
  • 1
    When you use dirs.ToString() as the input to your RegEx you're effectively searching against the string "System.String[]". You probably meant to run the RegEx for each item in the list instead? Commented Aug 20, 2018 at 15:42
  • Even if you could do this, strings are immutable meaning that folder = "whatever" won't change the source list. Commented Aug 20, 2018 at 15:52

1 Answer 1

1

All you need to do is this:

string[] directories = Directory.GetDirectories(myRootPath, "*", SearchOption.AllDirectories);

string findFolderNamePattern = @"((?i)mydomain.com|sitename(?-i))";
string replacement = " ";            

foreach (var directory in directories)
{
    var newFolder = Regex.Replace(directory, findFolderNamePattern, replacement);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. it works when I used to debug, it returns folder names. but never change their name at all!
@D.JCode What do you mean by "never change their name at all"? in debug what do you see in newFolder after Regex.Replace? The same value as in directory?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.