I need to create backup folders that increase in number. But I need to skip over gaps in numbering if they exist, and make the next folder name ONE higher than the highest numbered folder. For example if I have:
c:\backup\data.1 c:\backup\data.2 c:\backup\data.4 c:\backup\data.5
I need the next folder to be
c:\backup\data.6
The code below works but it feels awful clunky. Is there a better way to do this and still remain in .NET 2.0?
static void Main(string[] args)
{
string backupPath = @"C:\Backup\";
string[] folders = Directory.GetDirectories(backupPath);
int count = folders.Length;
List<int> endsWith = new List<int>();
if (count == 0)
{
Directory.CreateDirectory(@"C:\Backup\Data.1");
}
else
{
foreach (var item in folders)
{
//int lastPartOfFolderName;
int lastDotPosition = item.LastIndexOf('.');
try
{
int lastPartOfFolderName = Convert.ToInt16(item.Substring(lastDotPosition + 1));
endsWith.Add(lastPartOfFolderName);
}
catch (Exception)
{
// Just ignore any non numeric folder endings
}
}
}
endsWith.Sort();
int nextFolderNumber = endsWith[endsWith.Count - 1];
nextFolderNumber++;
Directory.CreateDirectory(@"C:\Backup\Data." + nextFolderNumber.ToString());
}
Thanks
Here’s a slightly different version, but basically does the same thing. Find the folder with the max suffix and then add one to that for the next folder.
I just ‘cleaned’ your code up a bit to remove the empty catch and the additional list / sort.