I would like to create a method which takes either a filename as a string
or a FileInfo
and adds an incremented number to the filename if the file
///
/// Create a unique filename for the given filename
///
/// A full filename, e.g., C:\temp\myfile.tmp
/// A filename like C:\temp\myfile633822247336197902.tmp
public string GetUniqueFilename(string filename)
{
string basename = Path.Combine(Path.GetDirectoryName(filename),
Path.GetFileNameWithoutExtension(filename));
string uniquefilename = string.Format("{0}{1}{2}",
basename,
DateTime.Now.Ticks,
Path.GetExtension(filename));
// Thread.Sleep(1); // To really prevent collisions, but usually not needed
return uniquefilename;
}
As DateTime.Ticks has a resolution of 100 nanoseconds, collisions are extremely unlikely. However, a Thread.Sleep(1) will ensure that, but I doubt that it's needed