Batch File Search and Renaming with C#

If it is necessary to rename a batch of files, where both the existing and new file names exist in an Excel spreadsheet, C# can be used to automate the renaming process.

In the example below, a spreadsheet called “Documents to rename.xlsx” contains the file name information. Column ‘A’ contains the existing file name, without the file extension, column ‘B’ contains the new file name, if available, without the extension, and column ‘C’ is for notes to be added during the renaming process.

Existing File Name New File Name Notes
OldFileName1 NewFileName1
OldFileName2
OldFileName3 NewFileName3
OldFileName4 NewFileName4

First of all, the path to the above document, as well as to the files to be renamed, is set and a check is made to see if they exist. If they do exist, the document containing the file names is opened and the file name information on the first sheet is processed. The last row used is obtained and all the rows, from the second to the last are handled one by one. The current and new file names are extracted from columns ‘A’ and ‘B’, using their numerical references, 1 and 2. A check is made to see if the file exists with the current name and if it does the file gets renamed to the new name, providing there is one available. Feedback is added in column 3 as to whether the file was renamed or not, or, if it had already been renamed. Overall feedback is also given as to the total number of files renamed.

using System;
using System.IO;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

namespace BatchFileSearchRename
{
    class Program
    {
        static void Main(string[] args)
        {

            // Excel.
            Excel.Application xlApp = new Excel.Application();

            // File names workbook.
            string pathNamesDoc;
            pathNamesDoc = @"C:\Demo\Rename\Documents to rename.xlsx";
            Excel.Workbook xlNamesWorkbook = null;
            Excel.Worksheet xlNamesWorksheet = null;

            // Path to documents to rename.
            string pathDocsRename;
            pathDocsRename = @"C:\demo\";

            // Check if the file and folder paths exist.
            if (File.Exists(pathNamesDoc) && Directory.Exists(pathDocsRename))
            {

                try
                {

                    // Open the file names workbook and assign to a variable.
                    xlNamesWorkbook = xlApp.Workbooks.Open(pathNamesDoc);

                }
                catch (Exception e)
                {

                    // Message stating that workbook can't be opened.
                    Console.WriteLine("Unable to open file names workbook.");

                    // Quit Excel and exit.
                    xlApp.Quit();
                    System.Environment.Exit(1);

                }

                // Select the first sheet.
                xlNamesWorksheet = xlNamesWorkbook.Sheets[1];

                // Last row and file name variables.
                long lastRow;
                string currentFileName;
                string newFileName;
                string fileExtension = ".docx";

                // Renamed file count.
                int filesRenamed = 0;

                // Find the last row used.
                lastRow = xlNamesWorksheet.UsedRange.Rows.Count;

                // Check if there are any files to rename.
                if (lastRow <= 1)
                {

                    // Message stating no files to rename.
                    Console.WriteLine("There are no files to rename.");

                }
                else
                {

                    // Process the rows, from second row to the last used.
                    for (int Row = 2; Row <= lastRow; Row++)
                    {

                        // Extract the current and new file name.
                        currentFileName = xlNamesWorksheet.Cells[Row, 1].Value;
                        newFileName = xlNamesWorksheet.Cells[Row, 2].Value;

                        // Check if the file exists and a new name has been provided.
                        if (File.Exists(
                            pathDocsRename + currentFileName + fileExtension) && 
                            !String.IsNullOrEmpty(newFileName))
                        {

                            // Check if the new file name is valid.
                            var isValid = 
                                newFileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0;

                            if (isValid)
                            {

                                try
                                {

                                    // Rename file.
                                    System.IO.File.Move(
                                        pathDocsRename + currentFileName + fileExtension,
                                        pathDocsRename + newFileName + fileExtension);

                                    // Add message to column 3 stating file has been renamed.
                                    xlNamesWorksheet.Cells[Row, 3].Value =
                                        "File has been renamed.";

                                    // Increment the files renamed count.
                                    filesRenamed += 1;

                                }
                                catch (Exception e)
                                {

                                    // Add message to column 3 stating file can't be renamed.
                                    xlNamesWorksheet.Cells[Row, 3].Value = 
                                        "File could not be renamed.";

                                }

                            }
                            else
                            {

                                // Add message in column 3 stating no new valid name 
                                // provided.
                                xlNamesWorksheet.Cells[Row, 3].Value = 
                                    "No new valid file name provided.";

                            }

                        }
                        else
                        {

                            // Check if new file name has been provided.
                            if (String.IsNullOrEmpty(newFileName))
                            {

                                // Add message in column 3 stating no new file name
                                // provided.
                                xlNamesWorksheet.Cells[Row, 3].Value =
                                    "No new valid file name provided.";

                            }
                            // Check if file has already been renamed.
                            else if (File.Exists(
                                pathDocsRename + newFileName + fileExtension))
                            {

                                // Add message in column 3 stating file already renamed.
                                xlNamesWorksheet.Cells[Row, 3].Value = 
                                    "File has already been renamed.";

                            }
                            else
                            {

                                // Add message in column 3 stating file does not exist.
                                xlNamesWorksheet.Cells[Row, 3].Value = 
                                    "File does not exist.";

                            }

                        }

                    }

                    try
                    {

                        // Save the file names workbook.
                        xlNamesWorkbook.Save();

                    }
                    catch (Exception e)
                    {

                        // Message stating file names workbook could not be saved.
                        Console.WriteLine("The file names workbook could not be saved.");

                    }

                    // Feedback on renamed files.
                    if (filesRenamed == 0)
                    {

                        Console.WriteLine("No files were renamed.");

                    }
                    else if (filesRenamed == 1)
                    {

                        Console.WriteLine(filesRenamed + " file renamed successfully.");

                    }
                    else
                    {

                        Console.WriteLine(filesRenamed + " files renamed successfully.");

                    }

                }

                // Close the file names workbook and quit Excel.
                xlNamesWorkbook.Close(false);
                xlApp.UserControl = true;
                xlApp.Quit();
                Marshal.ReleaseComObject(xlNamesWorksheet);
                Marshal.ReleaseComObject(xlNamesWorkbook);
                Marshal.ReleaseComObject(xlApp);

            }
            else
            {

                // Check if its the file or folder path that doesn't exist.
                if (!File.Exists(pathNamesDoc))
                {

                    // Error message if file names workbook doesn't exist.
                    Console.WriteLine("The document containing the file "
                        + "names does not exist.");

                }
                else
                {

                    // Error if folder path for documents to be renamed doesn't exist.
                    Console.WriteLine("The location of the files to rename " 
                        + "does not exist.");

                }

            }

            // Force console window to stay open until a key is pressed.
            Console.ReadKey();

        }

    }
}

Further Resources