Rename files after their modification dates in C#

[rename files]

Lately I’ve been creating one file a day and I wanted to rename the files after their modification dates. Something like “File 04-01-20.jpg.” So I wrote this program to do that.

Enter the directory that you want to search, a prefix for the file names, and a date format. Then click Search to see a list of the changes that the program will make. Check the boxes next to the commands that you want to execute and click Rename to rename the files.


When you click Search, the following code executes.

// List the renames that we will perform.
private void btnSearch_Click(object sender, EventArgs e)
{
    clbRenames.Items.Clear();

    Directory.SetCurrentDirectory(txtDirectory.Text);

    List<string> new_names = new List<string>();
    string prefix = txtPrefix.Text;
    string format = txtFormat.Text;
    foreach (string filename in Directory.GetFiles(txtDirectory.Text))
    {
        // Get the file's creation date.
        FileInfo file_info = new FileInfo(filename);
        DateTime date = file_info.LastWriteTime.Date;
        string new_name = prefix + date.ToString(format) +
            file_info.Extension;

        int i = 1;
        while (new_names.Contains(new_name))
        {
            new_name = prefix + date.ToString(format) +
                " (" + i.ToString() + ")" + file_info.Extension;
            i++;
        }
        new_names.Add(new_name);

        clbRenames.Items.Add(file_info.Name + " -> " + new_name);
    }
}

This code sets the program’s working directory to the directory that you entered. It then makes a list of strings to hold the new file names.

The code gets the file name prefix and date format that you entered, and then loops through the files in the directory. (You could make this more elaborate by making the search look for filenames matching a pattern.)

For each file, the program creates a FileInfo object and uses that object to get the file’s modification date. It then combines the filename prefix, the date (formatted using the format that you entered), and the file’s original extension to create the file’s new name.

The code then checks the new_names list to see if the program is already planning to give that name to a different file. If that name is already taken, the code enters a loop. Each time through the loop, the code adds a number to the end of the filename as in “File 04-01-20 (1).jpg,” “File 04-01-20 (2).jpg,” and so on until it finds a name that is not already reserved. When it finds a usable name, the program adds it to the new_names list. It then adds the file’s old and new names to the program’s CheckedListBox.

Note that this method does not detect existing files that already have the new name. If the directory starts with a file named “File 04-01-20.jpg,” then the program will try to reuse that name and will probably have problems. Ideally you will only use this program once on a given directory.

When you check some rename commands and click Rename, the following code executes.

// Rename the files.
private void btnRename_Click(object sender, EventArgs e)
{
    foreach (object command in clbRenames.CheckedItems)
    {
        string rename = command as string;
        string[] separators = { " -> " };
        string[] names = rename.Split(separators,
            StringSplitOptions.RemoveEmptyEntries);
        File.Move(names[0], names[1]);
    }

    int num_files = clbRenames.CheckedItems.Count;
    MessageBox.Show("Renamed " + num_files.ToString() + " files");
    clbRenames.Items.Clear();
}

This code loops through the items in the CheckedListBox that are checked. It splits each item’s text into the corresponding file’s old and new names, and then uses File.Move to rename the file.

The method finishes by showing the number of files that it moved.

Download the example program to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in files and tagged , , , , , , , , . Bookmark the permalink.

2 Responses to Rename files after their modification dates in C#

  1. Adrian says:

    Your program formats the dates as “MM-dd-yy” (I checked this by running the program in debug mode) on my computer. I wrote a similar program mainly for renaming photos and there I wanted file names that would sort nicely across multiple years. I also added the time into the new names; that would be a simply thing to add to your program. So I choose to give an explicit date format of “yyyy-MM-dd-HH-mm”.

    • RodStephens says:

      Yes, I wasn’t completely sure what format I wanted, and I knew others would want a different format. That’s why I made if let you specify the format in a textbox.

      The format you give certainly would work for sorting and handle multiple photos in the same day. (Sadly the program didn’t work well for me. For some reason, some photos came off my phone with the wrong dates, so I had to rename some by hand. Weird.)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.