1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
public static void Capitalize() { TextInfo oTextInfo = CultureInfo.CurrentCulture.TextInfo; StringBuilder oSb = new StringBuilder(); string Folder; var DirectoryToCapitalize = (from p in Directory.GetDirectories(@"C:\MyFiles", "*.*", SearchOption.AllDirectories) let directories = p.Substring(p.LastIndexOf("\\") + 1) let words = directories.Split(' ') from word in words where word.Length > 0 && char.IsLower(word[0]) group word by p into groupedChanges select new { Folder = groupedChanges.Key, Words = ( from p in groupedChanges where groupedChanges.Key.IndexOf("\\" + p) > 0 select "\\" + p) .Union( from p in groupedChanges where groupedChanges.Key.IndexOf(" " + p) > 0 select " " + p) }); foreach (var GroupItem in DirectoryToCapitalize) { Folder = GroupItem.Folder; foreach (var Word in GroupItem.Words) Folder = Folder.Replace(Word, oTextInfo.ToTitleCase(Word)); oSb.AppendLine(GroupItem.Folder); // Original path oSb.AppendLine(Folder); // New path // Can't rename C:\MyFiles\test to C:\MyFiles\Test // We need to rename the folder with a temp name and rename it back with capitalized words //Directory.Move(Folder, Folder + "1"); //Directory.Move(Folder + "1", Folder); } Console.WriteLine(oSb.ToString()); }
Refactorings
No refactoring yet !
I wrote a method to capitalize the first letter of each directories for a given path. I used it at the same time to work on my LINQ skills so don't remove it when refactoring please, improve it if necessary. I need to perform two different sub query to know if the word to capitalize is the first one or not, but I'm not sure if all this is really necessary. Also, I had to add a \ or a blank space before to word because I don't want to replace all 'a' because there is the word a in the folder name. See third directory name.
C:\MyFiles\Music\candlemass- ancient Dreams
C:\MyFiles\test\die apokalyptischen reiter - licht
C:\MyFiles\Music\a Dozen Furies - a Concept From Fire
I commented the two lines that rename the directory because I don't want to be responsable for renaming all your folders :)