Use regular expressions to rename files within a date range and that match a pattern in C#

example

This example extends the example Use regular expressions to rename files that match a pattern in C# to let you rename files within a date range. See the previous example for most of the details. This post describes the changes from that version.

The original program collected the names of files that matched a pattern. This example does, too, but it also collects the files’ last modification dates. It stores those date in a List<DateTime> named Dates.

The following code shows how the program builds its lists of file names and dates. The new code is shown in blue.

// Make a list of file names to change from and to.
private List<string> FullFromNames, FromNames, ToNames;
private List<DateTime> Dates;
private void MakeFileLists()
{
    try
    {
        // Make the file name lists.
        FullFromNames = new List<string>();
        FromNames = new List<string>();
        ToNames = new List<string>();
        Dates = new List<DateTime>();

        // Get the files that match the pattern and date range.
        DirectoryInfo dir_info = new DirectoryInfo(txtDirectory.Text);
        FileInfo[] files = dir_info.GetFiles(txtFilePattern.Text);
        Regex regex = new Regex(txtOldPattern.Text);

        DateTime from_date = DateTime.Parse(txtFromDate.Text).Date;
        DateTime to_date = DateTime.Parse(txtToDate.Text).Date;

        for (int i = 0; i < files.Length; i++)
        {
            string new_name = regex.Replace(files[i].Name,
                txtNewPattern.Text);
            new_name = new_name.Replace("$i", i.ToString());

            if (files[i].Name != new_name)
            {
                // Get the file's last modificaiton date.
                FileInfo file_info = new FileInfo(files[i].FullName);
                if ((file_info.LastWriteTime.Date >= from_date) &&
                    (file_info.LastWriteTime.Date <= to_date))
                {
                    FullFromNames.Add(files[i].FullName);
                    FromNames.Add(files[i].Name);
                    ToNames.Add(new_name);
                    Dates.Add(file_info.LastWriteTime);
                }
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error building file list.\n" + ex.Message);
        FullFromNames = new List<string>();
        FromNames = new List<string>();
        ToNames = new List<string>();
    }
}

In the first two changes, the program declares and initializes the Dates list.

Next the code gets the an array of FileInfo objects describing the files in the target directory. It then makes a RegEx representing the regular expression that the program will use to make file name replacements.

The code then gets the date range of interest. There’s a trick here that’s often useful when you’re dealing with dates. If you’re not careful, a DateTime object’s time values can mess up the program. For example, suppose you enter 9/12/14 as the end of the date range. Now suppose a file was last accessed on 9/12/14 at 11:00 AM. When you parse the end of the date range, you get 9/12/14 0:00:00 AM. That’s before the file’s last modification time, so the program won’t select that file even though you probably want to select files modified on that date.

To work around the time of day issue, the program uses only the date portions of the date range and the file modification times. If you look at the blue code, you’ll see how the program uses DateTime.Parse to get the date range values, and then uses the Date property to get only the date parts of those values.

After getting the date range, the code loops through the files that match the file pattern. The program gets each file’s FileInfo object and compares the Date only of its LastWriteTime to the desired date range. If the file’s modification time lies within the desired range, the program adds it to the file lists.

The rest of the program is similar to the previous example.


Download Example   Follow me on Twitter   RSS feed




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, regular expressions and tagged , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Use regular expressions to rename files within a date range and that match a pattern in C#

  1. Toni says:

    Hello, my name is toni, I’m Spanish.
    thanks for the examples from http://csharphelper.com
    I have little knowledge of visual basic and have found this example for visual basic http://csharphelper.com/blog/2014/09/use-regular-expressions-rename-files-within-date-range-match-pattern-c/
    But I don’t know how to convert it into Microsoft Visual Basic 2010 Express.
    I download the file howto_net_rename_files_with_regex2.rar but Microsoft Visual Basic 2010 Express cannot open it.

    You could do an example like that but rename folders and files.

    Thank you so much for everything

    regards

    • RodStephens says:

      Hi Toni,

      When you click the Download button, you should get a .zip file not a .rar file. File Explorer should be able to open it and make it look like a normal directory hierarchy, but Visual Studio cannot handle that.

      Instead right-click on the .zip file and select Extract All. Then double-click the .sln file in the unzipped folder. Most of my examples are in C# 2008 so they are easy to open in later versions. If you open it in C# 2010, it should upgrade the project for you.

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.