Saturday, March 23, 2013

Batch rename with leading zeroes

Let's say you're writing a batch rename function in C#, but you want the number in the filenames to have a leading zero, like this:
filename-01
filename-02
filename-03
etc. etc.

You need to find how many zeroes you need to add, based on the number of the total files, or you would end up with something like this:
filename-09
filename-010
filename-011
etc. etc.
Which looks bad, and it could give problems with some programs depending on how they sort a file list.
The result you want is one where the number's count is the same, indipendently from the number of files, even if you have a million files, it needs to work.
Doing an if/else is bad, because you would need to know the number of files before-hand. The solution is pretty simple, this is the result you will get:

filename-08
filename-09
filename-10
filename-11

Or, using larger numbers:

filename-0001
filename-0002
...
filename-0099
filename-0100
...
filename-0999
filename-1000
etc. etc. 
Let's see the code:

List<string> files = new List<string>(); //Our list of files

//populate the file list in any way you want, like this
private void populateFiles() 
{
    string dir = @"path\to\your\directory";
    foreach(string s in Directory.GetFiles(dir)) 
    {
        files.Add(s);
    }
    //Or you could do a files.AddRange(Directory.GetFiles(dir));
}

private void batchRename() 
{
    //Cycle every file in the list
    for (int i = 0; i < files.Count; i++)
    {
        //zeroesAmount contains the number of zeroes to add to the title
        //Let's say the files.Count is 758 and "i" is now at 19
        //We get the length of the string "758", which is 3
        //We get the length of the string "19", which is 2
        //We subtract them, 3 - 2 = 1, so it's 1 zero to add
        int zeroesAmount = files.Count.ToString().Length - i.ToString().Length;

        //This is the string that will be added to the file name
        string zeroes = "";

        //Actual cycle to add the zeroes number to the string
        for (int ii = 0; ii < zeroesAmount; ii++)
        {
            zeroes += "0";
        }

        //Assigning the new file name and renaming, with the File.Move function
        string parent = Directory.GetParent(files[i]);
        string fileName = Path.GetFileNameWithoutExtension(files[i]);
        string extension = Path.GetExtension(files[i]);
        string newFile = parent + "\\" + fileName + "-" + zeroes + i.ToString() + extension;
        if (!File.Exists(newFile))
        {
            File.Move(files[i], newFile);
        }
    }
}

No comments:

Post a Comment

prettyprint