Skip to content

Instantly share code, notes, and snippets.

@lakario
lakario / gist:5007434
Last active December 14, 2015 01:39
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) ?? "";