Use regular expressions to rename files in a directory hierarchy in C#


example

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

The earlier versions of this program only searched a single directory. This version only makes one small change to let you search recursively through a directory hierarchy. When it lists the files that it will update, this version of the program uses the following code.

// Get the files that match the pattern and date range.
DirectoryInfo dir_info = new DirectoryInfo(txtDirectory.Text);
SearchOption option = SearchOption.TopDirectoryOnly;
if (radAllDirectories.Checked) option = SearchOption.AllDirectories;
FileInfo[] files = dir_info.GetFiles(txtFilePattern.Text, option);
Regex regex = new Regex(txtOldPattern.Text);

The code highlighted in blue shows the changes. The program sets the variable option to TopDirectoryOnly. Then if the All Directories radio button is checked, the code changes the option to AllDirectories.

The program then passes the option into the call to GetFiles so that method can search either the subdirectories if appropriate.

The rest of the program is unchanged. See the previous example and download this program to see all of the details.


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.