Skip to content

Instantly share code, notes, and snippets.

@lakario
Last active December 14, 2015 01:39
Show Gist options
  • Select an option

  • Save lakario/5007434 to your computer and use it in GitHub Desktop.

Select an option

Save lakario/5007434 to your computer and use it in GitHub Desktop.
C# code to generate a unique variation from a provided filename. Works by appending or matching an iterator on the end of the file name.
public static string GetUniqueFileName(string filePath, char directorySeparatorChar = '\\')
{
if (String.IsNullOrWhiteSpace(filePath))
return filePath;
const string iteratorRegex = @"(-(?<iterator>[0-9]+)|\((?<iterator>[0-9]+)\))$";
var fileName = Path.GetFileNameWithoutExtension(filePath) ?? string.Empty;
var directoryName = Path.GetDirectoryName(filePath);
var fileExtension = Path.GetExtension(filePath) ?? "";
var match = Regex.Match(fileName, iteratorRegex);
var iteratorValue = 1;
if (match.Success) {
iteratorValue = int.Parse(match.Groups["iterator"].Value) + 1;
fileName = fileName.Substring(0, match.Groups["iterator"].Index - 1);
}
var newFileName = String.Concat(String.Format("{0}-{1}", fileName, iteratorValue), fileExtension).ToLowerInvariant();
return String.Concat(directoryName, (!String.IsNullOrEmpty(directoryName) ? directorySeparatorChar.ToString() : ""), newFileName).Replace(Path.DirectorySeparatorChar, directorySeparatorChar);
}
@lakario

lakario commented Feb 21, 2013

Copy link
Copy Markdown
Author

Example inputs and outputs

  • hello.txt ---> hello-1.txt
  • hello-1.txt ---> hello-2.txt
  • hello(2).txt ---> hello-3.txt

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment