Rename Files by a Console Application in C#

Zhen Yuwang, 22 May 2012

Renaming 1 file name is extremely simple, while renaming lots of files’ name is kind of troublesome task. This blog will introduce an alternative way to solve this problem using console application in C#.

First of all, let’s see what we need to do in below example. Assume we have a folder full of files with weird names. They have no extension as well.

 Rename Files by a Console Application in C#

In the meantime, we have another spread sheet contains all expected file names in same folder.

 Rename Files by a Console Application in C#

So create a C# console application in VS 2008, create a new file “App.config”, and add some keys like this.

<add key="filePath" value="C:\Users\Administrator\Desktop\Temp\Test Tool"/>
<add key="CSVFile" value="Attachment.csv"/>

These indicate where spread sheet stored so that user can modify the location outside the “Program.cs”.

Next, read the spread sheet location from “App.config” into “Program.cs”.

string filePath = ConfigurationManager.AppSettings["filePath"];
string CSVFile = ConfigurationManager.AppSettings["CSVFile"];

Define a StreamReader and StreamWriter.

StreamReader sr = new StreamReader(filePath + "\\" + CSVFile);
StreamWriter sw = new StreamWriter(filePath + "\\" + CSVFile.Replace(".", " - new."));

These codes will create another spread sheet file with name “Attachment - new.csv”. It is necessary because there are some target files could have some names. For instance, there are 2 “Acceptance Letter FINAL (2)”. But we cannot have 2 files with same name in one folder.

Read each line from spread sheet

while ((line = sr.ReadLine()) != null)

Check file name exist or not.  If exists, give a new unique name using the count number i.

if (File.Exists(fileName))
fileName = fileName.Replace(".", " - " + i + "."); 

Rename the target files and write new names into new spread sheet

File.Move(fileId, fileName);
sw.WriteLine(newLine); 

Run it and check what we get.
 Rename Files by a Console Application in C#

To sum up, this blog just show several code snippets and give an idea of solution. If you have any questions, please don’t hesitate to contact us.