Click here to Skip to main content
15,881,730 members
Articles / Programming Languages / C#
Tip/Trick

Rename files recursively with formatted name in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
2 Oct 2011CPOL 19.2K   3   1
Rename all the files from the given folder using C#. The code will go through all the files and rename with the same name but with formatted name for example by removing "-" or "_" etc with given characters..
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:
C#
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:
C#
/// <summary>
/// It will rename filename into title case format.
/// </summary>
/// <param name="directoryName">Directory in where this rename process will take place to rename all the containing files.</param>
/// <param name="predicate">
/// If it requires to do extra formatting for example, replace special charecters from the filename
/// then consumer of this method can pass filtering behavior via this predicate.
/// </param>
public static void RenameFilesToTitleCase(string directoryName, Func<string, string> predicate)
{
    Rename(directoryName, predicate, System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase);
}

/// <summary>
/// It will rename filename into lower case format.
/// </summary>
/// <param name="directoryName">Directory in where this rename process will take place to rename all the containing files.</param>
/// <param name="predicate">
/// If it requires to do extra formatting for example, replace special charecters from the filename
/// then consumer of this method can pass filtering behavior via this predicate.
/// </param>
public static void RenameFilesToLowerCase(string directoryName, Func<string, string> predicate)
{
    Rename(directoryName, predicate, System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToLower);
}

/// <summary>
/// Rename the filenam with the new name based on the condition provided by predicate and casePredicate.
/// </summary>
/// <param name="directoryName">Directory in where this rename process will take place to rename all the containing files.</param>
/// <param name="predicate">Extra formatting to the filname.</param>
/// <param name="casePredicate">This will point to the case changing method passed by calling method.</param>
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)));
        });
    });
}

/// <summary>
/// To get the new renamed filename.
/// </summary>
/// <param name="predicate">Formatting condition</param>
/// <param name="directory">The directory for which this rename will take place.</param>
/// <param name="file">Formatted filename</param>
/// <returns>This method will return formatted renamed filenamed combined with directoryname.</returns>
private static string GetNewFileName(Func<string, string> predicate, string directory, string file)
{
    return Path.Combine(Path.GetFullPath(directory), Filter(Path.GetFileName(file), predicate));
}

/// <summary>
/// To execute calling method provided formatting method.
/// </summary>
/// <param name="data">Filename to format</param>
/// <param name="predicate">The delegate of the filename formatter.</param>
/// <returns>Formatted filename.</returns>
private static string Filter(string data, Func<string, string> predicate)
{
    return !ReferenceEquals(predicate, null) ? predicate(data) : data;
}

Usage:
C#
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);
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Australia Australia

Comments and Discussions

 
QuestionWhat about rename an xml Pin
Asholino9-Jan-19 6:17
Asholino9-Jan-19 6:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.