Created
December 8, 2014 09:55
-
-
Save raducugheorghe/4f28ecb64beac5d0dd2d to your computer and use it in GitHub Desktop.
[C#] Ensure file name is unique at a given path (puts <filename (count).ext>)
This file contains 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
private string EnsureFileNameDoesNotExist(string storagePath, string fileName) | |
{ | |
while (System.IO.File.Exists(Path.Combine(storagePath, fileName))) | |
{ | |
var extension = Path.GetExtension(fileName); | |
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); | |
var fileCountMarker = new Regex("\\((?<count>[0-9]+)\\)$"); | |
var matchResult = fileCountMarker.Match(fileNameWithoutExtension); | |
if (matchResult.Success) | |
{ | |
int counter; | |
var matchValue = matchResult.Value; | |
if (Int32.TryParse(matchValue.Replace("(", String.Empty).Replace(")", String.Empty), out counter)) | |
{ | |
fileName = fileName.Replace(matchValue, String.Format("({0})", ++counter)); | |
} | |
} | |
else | |
{ | |
fileName = String.Format("{0} (2){1}", fileNameWithoutExtension, extension); | |
} | |
} | |
return fileName; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment