[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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


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 that 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 the subdirectories if appropriate.

The rest of the program is unchanged.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.