我需要创建数量增加的备份文件夹。但是如果存在编号间隙,我需要跳过它们,并使下一个文件夹名称比编号最高的文件夹高一个。例如,如果我有:
c:\备份\数据.1 c:\备份\数据.2 c:\备份\数据.4 c:\备份\数据.5
我需要下一个文件夹
c:\备份\数据.6
下面的代码有效,但感觉非常笨拙。有没有更好的方法来做到这一点并且仍然保留在 .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());
}
谢谢