Batch File Renaming with C#

Below is an example of how Microsoft Excel files can be renamed in a batch, based on the contents of a particular cell within each file.

Firstly, the file path is set and a check is carried out to make sure that the path exists. This is followed by a check to make sure that there are files to process at the desired location. Each file is then processed one by one. All files without a ‘.xlsx’ extension are ignored. If the value in the specified cell of the first sheet in each individual file is populated and it contains only valid characters then the file is renamed and a message is displayed confirming each name change, otherwise a message is displayed stating that a particular file name could not be changed. Finally, a count of the number of files that have been renamed is displayed.

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

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

            // File path.
            string filePath = @"C:\demo\";

            // File extension.
            string fileExtension;

            // Check to see if the file path exists.
            if (Directory.Exists(filePath))
            {

                // Return the names of the files at the specified path.
                string[] dirFiles = Directory.GetFiles(filePath);

                // Check if there are any files at the path.
                if (dirFiles.Length == 0)
                {

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

                }
                else
                {

                    // Excel file variables.
                    Excel.Application xlApp = new Excel.Application();
                    Excel.Workbook xlWorkbook;
                    Excel.Worksheet xlWorksheet;
                    string newFileName;

                    // Renamed file count.
                    int filesRenamed = 0;

                    // Process the files at the path.
                    foreach (string dirFile in dirFiles)
                    {

                        // Extract the file extension from the name.
                        fileExtension = Path.GetExtension(dirFile);

                        // Check if the file is an Excel file.
                        if (fileExtension == ".xlsx" && !dirFile.Contains("~"))
                        {

                            // Open the Excel file and select sheet 1.
                            xlWorkbook = xlApp.Workbooks.Open(@dirFile);
                            xlWorksheet = xlWorkbook.Sheets[1];

                            // Check if there is a value is cell A1.
                            if (xlWorksheet.Cells[1, 1].Value != null)
                            {

                                // Construct new file name from value in cell A1.
                                newFileName = xlWorksheet.Cells[1, 1].Value.ToString() + ".xlsx";

                                // Check if the new file name is valid.
                                var isValid = !string.IsNullOrEmpty(newFileName) &&
                                    newFileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&
                                    !File.Exists(Path.Combine(filePath, newFileName));

                                if (isValid)
                                {

                                    try
                                    {

                                        // Close the workbook.
                                        xlWorkbook.Close();

                                        // Rename the file.
                                        System.IO.File.Move(dirFile, filePath + @"\" 
                                            + newFileName);

                                        // Message confirming file has been renamed.
                                        Console.WriteLine("The file \"{0}\" has been renamed to " 
                                            + "\"{1}\".", dirFile.ToString(), newFileName);

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

                                    }
                                    catch (Exception e)
                                    {

                                        // Message confirming the file could not be renamed.
                                        Console.WriteLine("The file \"{0}\" could not be " +
                                            "renamed.", dirFile.ToString());

                                    }

                                }
                                else
                                {

                                    // Close the workbook.
                                    xlWorkbook.Close();

                                    // Message confirming the file could not be renamed.
                                    Console.WriteLine("The file \"{0}\" could not be renamed.",
                                        dirFile.ToString());

                                }

                            }
                            else
                            {

                                // Close the workbook.
                                xlWorkbook.Close();

                            }

                        }

                    }

                    // Message stating the number of files renamed.
                    if (filesRenamed == 0)
                    {
                        Console.WriteLine("No files have been renamed.");
                    }
                    else if (filesRenamed == 1)
                    {
                        Console.WriteLine("{0} file has been renamed.", filesRenamed);
                    }
                    else
                    {
                        Console.WriteLine("{0} files have been renamed.", filesRenamed);
                    }

                }

            }
            else
            {

                // Display a message stating file path does not exist.
                Console.WriteLine("File path does not exist.");

            }

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

        }
    }
}

Further Resources