How to Use regular expressions to rename files within a date range and that match a pattern in C# – Programming, Pseudocode Example, C# Programming Example
C# Windows Form

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

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 that 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.

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 the example to experiment with it and to see additional details.

1 Comment

Leave a Comment

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