I have over 2500 files in a directory tree- some of them are numbered, some of them aren't. eg.
1. That night it rained.epub
The sparrow returns at dawn.epub
001. Tomorrow is a new day.epub
000.1. We are the children.epub
I created my C# code to iterate through all the directories and rename the numbered files to look neater, but at the same time should leave the unnumbered file unaltered like so:
001. That night it rained.epub
The sparrow returns at dawn.epub
001. Tomorrow is a new day.epub
000.1. We are the children.epub
My coding looks like this:
class Program
{
static string path = @"C:\Users\Anja\Desktop\reekse";
static string name;
static string rpath;
static int numberperiod;
static string number;
static string newname;
static string movepath;
static void Main(string[] args)
{
foreach (var file in Directory.GetFiles(path, "*.epub", SearchOption.AllDirectories)) //searches for all the epub files even if there are 20 subdirectories between the file and the main directory
{
name = System.IO.Path.GetFileName(file);//gets the filename sans the path
rpath = System.IO.Path.GetDirectoryName(file);//gets the path sans the file
numberperiod = name.IndexOf(".");//find the location of the 1st . (remember-zerobasing is used)
if (numberperiod == 1)//first period - meaning no 0's is used in numbering
{
number = name.Substring(0, numberperiod + 1);//pick up the number as well as the . that follows the numbering
name = name.TrimStart(number.ToCharArray());//convert the number to char and trim it
name = name.TrimStart('.', ' ', ' ');// remove any potential blankspaces and . that may be at the start of the filename
newname = "00" + number + " " + name; // create a name that has the 0's, the number, adequite spacing, and the name
}
if (numberperiod == 2)//same as above but the numbering contains two digits
{
number = name.Substring(0, numberperiod + 1);
name = name.TrimStart(number.ToCharArray());
name = name.TrimStart('.', ' ', ' ');
newname = "0" + number + " " + name;
}
if (numberperiod == 3)//files containing 3 digits
{
number = name.Substring(0, numberperiod + 1);
if (number == "000.")// in case the file has odd numbering as in the example
{
number = name.Substring(0, numberperiod + 3);
name = name.TrimStart(number.ToCharArray());
name = name.TrimStart('.', ' ', ' ');
newname = number + " " + name;
}
else
{
name = name.TrimStart(number.ToCharArray());
name = name.TrimStart('.', ' ', ' ');
newname = number + " " + name;
}
}
Console.WriteLine(newname.ToString());
movepath = Path.Combine(rpath, newname);
File.Move(file, movepath);
}
}
}
The coding works perfectly fine, but it just seems so tedious; I'm positive that there must be a simpler way of doing this like regex or Linq.
Can someone please help? I'm not any good when it comes to either Linq or regex. Can someone please help me rewrite this code to make it simpler?