[C# Helper]
Index Books FAQ Contact About Rod
[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]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

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

Title: Number files in a directory in C#

[Number files in a directory in C#]

I recently went on a trip where I took almost a thousand pictures. My phone (which has a pretty good camera) gives the pictures file names such as WP_20151106_22_04_47_Pro.jpg. I wanted an easy way to number files so they have more meaningful names such as HimejiCastle01.jpg or Food007.jpg.

This example lets you select a directory and then changes the names off the files in it so they include a base name (such as "Himeji Castle") and an increasing number.

Enter or select the directory name. Then enter a base name and a starting number. When you click List, the program lists the files in the directory and shows the names it will give them. If you like the results, click Rename to rename the files.

The following code executes when you click the List button.

private void btnList_Click(object sender, EventArgs e) { lvwFiles.Items.Clear(); string[] filenames = Directory.GetFiles(txtDirectory.Text); if (filenames.Length == 0) return; Array.Sort(filenames); int index = int.Parse(txtStartAt.Text); string format = "{0:D" + txtStartAt.Text.Length.ToString() + "}"; string base_name = txtBaseName.Text; List<string> old_names = new List<string>(); foreach (string filename in filenames) { string old_name = Path.GetFileName(filename); old_names.Add(old_name); ListViewItem item = lvwFiles.Items.Add(old_name); string new_name = base_name + string.Format(format, index) + Path.GetExtension(filename); if (old_names.Contains(new_name)) { MessageBox.Show("Name " + new_name + " is already in use."); break; } item.SubItems.Add(new_name); index++; } lvwFiles.Columns[0].AutoResize( ColumnHeaderAutoResizeStyle.ColumnContent); lvwFiles.Columns[1].AutoResize( ColumnHeaderAutoResizeStyle.ColumnContent); btnRename.Enabled = true; }

This code uses Directory.GetFiles to get an array of the files in the directory. It then uses Array.Sort to sort the file names.

Next the code parses the text entered in the Start At text box. It makes a formatting string to format numbers with the length of the text in that text box. For example, if you enter 000, the format string is {0:D3}. When it later uses this string to format numbers, the results are 3 digits long.

The code then loops through the file names. For each name it gets the file's current name without the directory path and adds it to the ListView. It then creates the new file name. If the new name is already in the list of current names, the program complains because it might be unable to rename the file to have the new name. (It might succeed depending on the order in which the files are renamed, but the program just assumes it won't work.) If the name is okay, the program adds it in the second ListView column.

Finally the code resizes the ListView columns so they are big enough to display their data.

When you click the Rename button, the following code executes.

private void btnRename_Click(object sender, EventArgs e) { string dirname = txtDirectory.Text; foreach (ListViewItem item in lvwFiles.Items) { string old_name = Path.Combine(dirname, item.Text); string new_name = Path.Combine(dirname, item.SubItems[1].Text); File.Move(old_name, new_name); } int num_files = lvwFiles.Items.Count; lvwFiles.Items.Clear(); btnRename.Enabled = false; MessageBox.Show("Renamed " + num_files.ToString() + " files."); }

This code gets the directory name and then loops through the items in the ListView control. It combines the directory path with the current and new file names in the ListView and then uses File.Move to rename the files. The code finishes by clearing the ListBox and displaying a success message.

The program has a few other useful features. For example, the ellipsis button lets you browse for a directory and the program saves and restores its size and position when it starts and stops.

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

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