The objective of this file rename operation program is as below:
- Rename recursively all the files inside a folder and also for the nested folders(if any exists).
- Change the case of the file name into two different formats: a. TitleCase, b. LowerCase
- Also format the file name with special formatting, for example, remove the "_" or "-" or "," from the file name etc. and this formatting condition could be pass via predicate from the calling function.
It is mentioned that this rename code will keep the file name same but with additional formatted name for example, if the file name is CLR_VIA_C#, then based on the following condition:
RenameFilesToTitleCase("C:\\CodeProject\\Tips\\Rename", (data) =>
{
return data.Contains("-") ? data.Replace("_", "") : data;
});
the new file name will be as Clr Via C#. The following code block will do the rename operation:
public static void RenameFilesToTitleCase(string directoryName, Func<string, string> predicate)
{
Rename(directoryName, predicate, System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase);
}
public static void RenameFilesToLowerCase(string directoryName, Func<string, string> predicate)
{
Rename(directoryName, predicate, System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToLower);
}
private static void Rename(string directoryName, Func<string, string> predicate, Func<string, string> casePredicate)
{
Directory.GetDirectories(directoryName).AsParallel().ToList().ForEach(directory =>
{
if (Directory.GetDirectories(directory).Count() > 0)
Rename(directory, predicate, casePredicate);
Directory.GetFiles(directory).AsParallel().ToList().ForEach(file =>
{
File.Move(file, casePredicate(GetNewFileName(predicate, directory, file)));
});
});
}
private static string GetNewFileName(Func<string, string> predicate, string directory, string file)
{
return Path.Combine(Path.GetFullPath(directory), Filter(Path.GetFileName(file), predicate));
}
private static string Filter(string data, Func<string, string> predicate)
{
return !ReferenceEquals(predicate, null) ? predicate(data) : data;
}
Usage:
class Program
{
static void Main(string[] args)
{
RenameFilesToTitleCase("C:\\CodeProject\\Tips\\Rename", (data) =>
{
return data.Contains("-") ? data.Replace("-", "__") : data;
});
RenameFilesToTitleCase("C:\\CodeProject\\Tips\\Rename", null);
}
}