Hi, I have coded a simple solution for you.. every time you check the file name you need to check for the latest number that's why your code is not checking beyond 1.
private string GetUniqueName(string name, string folderPath, string extension)
{
string validatedName = name;
string [] dirs = Directory.GetFiles(folderPath, name + "*" + extension);
if (dirs.Count() > 0)
{
Array.Sort(dirs);
string CurrentLastFile = dirs[dirs.Length -1];
Match m = Regex.Match(CurrentLastFile, "\\d+");
int number = m.Value == "" ? 0 : Convert.ToInt32(m.Value);
validatedName = string.Format("{0} [{1}]", name, number + 1);
}
return validatedName;
}
First I am getting all the available files in the same name format from the directory then I am getting the last file name from the list and get the number associated with it. The new file name will be formed based on the last file name.. Hope you get the idea..