Rename Folders Omitting Anything After [ RRS feed

  • Question

  • We have some folders (close to 500ish) that a disgruntled co-worker went in and added either a [ or  ( symbol with random text after the actual file name so that automated procedures will not work as the folder "Doesn't Exist"  

    Is thier a way in C# to take the folder name and Trim anything after a [ or a ( Keeping everything to the left of either of those characters?

    Wednesday, August 26, 2015 12:09 PM


  • I wrote a solution from what I understood from your question.

     static void RenameDirs()
                var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                var path = Path.Combine(desktop, "YourFoldername");
                DirectoryInfo dirInfo = new DirectoryInfo(path);
                var dirs = dirInfo.GetDirectories();
                Regex trimRegex = new Regex("(\\[|\\().*");
                foreach (var item in dirs)
                    string DirNewName = "";
                    string rep = trimRegex.Match(item.Name).Value;
                    if (rep.Length > 0)
                        DirNewName = item.Name.Replace(rep, string.Empty);
                        string newDirPath = Path.Combine(path, DirNewName);
    • This code check fodlers inside of your desktop with folder name "YourFoldername.
    • It seeks for directories containing '(' or '[' characters 
    • If directory contains those characters , than removes the string after start of any of those characters 
    • Directory containing those characters will be renamed

    Wednesday, August 26, 2015 12:48 PM