Introduction
This tip allows us to rename multiple files at a time. This helps us to learn how to use console commands in C# and the basics of background workers. Some of us may spend a lot of time renaming files. This application allows us to rename multiple files at a time.
Background
I must rename many documents in my office. For renaming, it may take too much time to do it. Or I need to depend upon another third-party application. So I decided to create my own application.
Using the Code
Let me explain my application in a step-by-step manner.
Step 1
I have created an empty form. In the form, I have placed a 2 Command buttons, a Background Worker, a FolderBrowserDialog and a GridView as shown below:
Step 2
Create an Excel file that can have an old file name and a new file name, then import the Excel file into the GridView.
Step 3
Call the folderbrowserdialog to choose the file to be renamed.
Step 4
Then, I have entered the file rename code in a renamer method as below:
- int datas=dataGridView1.Rows.Count;
- for(int i=0;i<=datas-1;i++)
- {
- String oldname,newname;
- oldname=dataGridView1.Rows[i].Cells[0].Value.ToString();
- newname=dataGridView1.Rows[i].Cells[1].Value.ToString();
- System.Diagnostics.Process process = new System.Diagnostics.Process();
- System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
- startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
- startInfo.FileName = "cmd.exe";
- startInfo.WorkingDirectory=@""+location+"";
- startInfo.Arguments = "/k Rename "+oldname+" "+newname;
- process.StartInfo = startInfo;
- process.Start();
- }
First, I have counted the number of rows available in Excel and then assigned that value to an integer.
- int datas=dataGridView1.Rows.Count;
I have used a loop to execute depending on the number of rows available in the GridView. This helps us to execute all the values available in the GridView.
- for(int i=0;i<=datas-1;i++)
Then, I have taken the old filename and the new filename from the GridView rows.
- String oldname,newname;
- oldname=dataGridView1.Rows[i].Cells[0].Value.ToString();
- newname=dataGridView1.Rows[i].Cells[1].Value.ToString();
Then, I created an object for the process and startinfo.
- System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
- System.Diagnostics.Process process = new System.Diagnostics.Process();
Open the command prompt using the following code:
- startInfo.FileName = "cmd.exe";
Set the working directory:
- startInfo.WorkingDirectory=@""+location+"";
Send the Argument to rename the file using the following line:
- startInfo.Arguments = "/k Rename "+oldname+" "+newname;
I have explained only the Rename code.
References