Skip to content

Instantly share code, notes, and snippets.

@raducugheorghe
Created December 8, 2014 09:55
Show Gist options
  • Save raducugheorghe/4f28ecb64beac5d0dd2d to your computer and use it in GitHub Desktop.
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>)
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