Official BV Software Blog
New, Updates and Anything else we find interesting

Quick program to batch rename files to replace text

February 23, 2008 14:42 by mmcconnell1618

Today I had a huge directory of 300+ images that I batch converted in Photoshop from TIFF to PNG format. The problem was I must have missed something in Photoshop and all the files came out like this:

 Image1.TIFF.PNG

I needed to remove the ".TIFF" part from the name so I wrote a quick c# command line program to look at a directory, find all files that contained text in their name and replace that with something else. It's a quick and dirty solution but I thought someone else might need it. The source directory, text to find and text to replace are just string in the source code. You may want to move them out to command line parameters if you need this kind of program often.

Here's the source code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

 

namespace FileNameChanger

{

    class Program

    {

        static void Main(string[] args)

        {

            /*

            * Change these three settings to tell the program

            * where to search, what to find and what to replace

            * it with

            */

            string sourceDir = @"C:\Users\mmcconnell\Desktop\CroppedTiff\PNG";

            string stringToFind = ".tiff.png";

            string stringToReplace = ".png";

 

            if (Directory.Exists(sourceDir))

            {

                string[] thefiles = Directory.GetFiles(sourceDir);

                if (thefiles != null)

                {

                    foreach (string f in thefiles)

                    {

                        string pathPart = Path.GetDirectoryName(f);

                        string filePart = Path.GetFileName(f);

                        filePart = filePart.Replace(stringToFind, stringToReplace);

                        File.Move(f, Path.Combine(pathPart, filePart));

 

                        Console.WriteLine("Moving to " + filePart);

                    }

                }

            }

        }

    }

}

 

 

 

Program.cs (1.26 kb)


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Related posts

Comments are closed