Every now and again, you are doing something and you need a small screwdriver instead of a hammer. I've been working on a lot of repetitive API work where I end up copying a set of files, renaming them, and then editing them. While I should just write a factory to handle these things, in the meantime I wanted to simplify my rename of a batch of files. So I wrote a little console app for batch renaming (download an executable here). The whole of the code is only 60 lines and that's because I wanted to include a help. So, you can cut and paste from here if you want:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace bRenamer
{
class Program
{
static void Main(string[] args)
{
if (args.GetUpperBound(0) != 2)
{
System.Version AppVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
Console.Clear();
Console.WriteLine("{4}\tVersion: {0}.{1}.{2}.{3}", AppVersion.Major.ToString(), AppVersion.Minor.ToString(),
AppVersion.Build.ToString(), AppVersion.Revision.ToString(), System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name);
Console.Write("\r\n\r\n{0}", System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name);
Console.Write(" path oldmatch newmatch\r\n");
Console.Write("where Path is a legitimate file path\r\n");
Console.Write("OldMatch is a case sensitive text of what you want to replace in the file name\r\n");
Console.Write("NewMatch is a what you want to use in the file name\r\n\r\n");
Console.Write(@"{0} c:\test old newandimproved would change a file named thisoldhouse.txt to thisnewandimprovedhouse.txt\r\n", System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name);
}
else
{
string path = args[0];
string oldMatch = args[1];
string newMatch = args[2];
if (Directory.Exists(path))
{
foreach (string fileName in Directory.GetFiles(path))
{
FileInfo fi = new FileInfo(fileName);
try
{
if (fi.Name.Contains(oldMatch))
{
Console.WriteLine("Renaming {0} to {1}", fi.Name, fi.Name.Replace(oldMatch, newMatch));
File.Move(fi.FullName, (path.EndsWith(@"\") ? path : path + @"\") + fi.Name.Replace(oldMatch, newMatch));
}
else
Console.WriteLine("Skipping {0} ", fi.Name);
}
catch { }
}
}
else
{
Console.WriteLine("{0} is not a valid directory", path);
}
Console.WriteLine("\r\nDone!");
}
}
}
}