I\'m developing a Windows application in VS2005 using C#. In my project, I generate dlls and store them in a directory. The dlls will be named as TestAssembly1, TestAssembly
Instead of lots of checking if a file already exist you can get a list of all assemblies, extract their ID's and return the highest ID + 1:
int nextId = GetNextIdFromFileNames(
"pathToAssemblies",
"TestAssembly*.dll",
@"TestAssembly(\d+)\.dll");
[...]
public int GetNextIdFromFileNames(string path, string filePattern, string regexPattern)
{
// get all the file names
string[] files = Directory.GetFiles(path, filePattern, SearchOption.TopDirectoryOnly);
// extract the ID from every file, get the highest ID and return it + 1
return ExtractIdsFromFileList(files, regexPattern)
.Max() + 1;
}
private IEnumerable ExtractIdsFromFileList(string[] files, string regexPattern)
{
Regex regex = new Regex(regexPattern, RegexOptions.IgnoreCase);
foreach (string file in files)
{
Match match = regex.Match(file);
if (match.Success)
{
int value;
if (int.TryParse(match.Groups[1].Value, out value))
{
yield return value;
}
}
}
}