Last active
December 14, 2015 01:39
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example inputs and outputs