Skip to content

Instantly share code, notes, and snippets.

@DTTerastar
Last active January 4, 2016 06:49
Show Gist options
  • Save DTTerastar/8584167 to your computer and use it in GitHub Desktop.
Save DTTerastar/8584167 to your computer and use it in GitHub Desktop.
EnsureUniqueFilename helps to generate a unique filename
public class EnsureUniqueFilename
{
private readonly string _path;
private readonly Dictionary<string, bool> _used = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
private string _format = "{0}_{1}{2}";
private int _startingSeq = 2;
public EnsureUniqueFilename(string path)
{
_path = path;
}
public string Seperator
{
set { Format = "{0}" + value + "{1}{2}"; }
}
public int StartingSeq
{
get { return _startingSeq; }
set { _startingSeq = value; }
}
public string Format
{
get { return _format; }
set { _format = value; }
}
public void MarkUsed(string fname)
{
_used[fname] = true;
}
public string GetFilename(string suggested)
{
var seq = GetStartingSeq(suggested);
RemoveSuffix(ref suggested, seq);
string fname = suggested;
while (AlreadyUsed(fname))
fname = string.Format(Format, Path.GetFileNameWithoutExtension(suggested), seq++, Path.GetExtension(suggested));
_used[fname] = true;
return fname;
}
private int GetStartingSeq(string suggested)
{
var matchCollection = Regex.Matches(suggested, "[0-9]+").Cast<Match>().LastOrDefault();
if (matchCollection == null) return StartingSeq;
int seq;
return !int.TryParse(matchCollection.Value, out seq) ? StartingSeq : seq;
}
private void RemoveSuffix(ref string fname, int seq)
{
var suffix = string.Format(Format, "", seq, "");
var name = Path.GetFileNameWithoutExtension(fname);
var ext = Path.GetExtension(fname);
if (name != null && name.EndsWith(suffix))
fname = name.Substring(0, name.Length - suffix.Length) + ext;
}
private bool AlreadyUsed(string suggested)
{
if (_path != null) return File.Exists(Path.Combine(_path, suggested));
bool alreadyUsed;
return _used.TryGetValue(suggested, out alreadyUsed) && alreadyUsed;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment