I\'ve seen several suggestions on naming files randomly, including using
System.IO.Path.GetRandomFileName()
or using a
Sy
Use an Int and increment it for each file.
I hope this self iterative function will help someone to generate a unique filename.
public string getUniqueFileName(int i, string fullpath, string filename)
{
string lstDir = fullpath.Substring(0, fullpath.LastIndexOf('\\'));
string name = Path.GetFileName(fullpath);
string path = fullpath;
if (name != filename)
path = Path.Combine(lstDir, filename);
if (System.IO.File.Exists(path))
{
string ext = Path.GetExtension(name);
name = Path.GetFileNameWithoutExtension(name);
i++;
filename = getUniqueFileName(i, fullpath, name + "_" + i + ext);
}
return filename;
}
If you control the directory, you could name your file based on the lastWriteTime:
DirectoryInfo info = new DirectoryInfo(directoryPath);
long uniqueKey = info.LastWriteTime.Ticks+1L;
string filename = String.Format("file{0}.txt", key);
But you have to check performances of this code: I guess building a DirectoryInfo does not come for free.
A GUID would be extremely fast, since it's implementation guarantees Windows can generate at least 16,384 GUIDS in a 100-nanosecond timespan. (As others pointed out, the spec doesn't guarantee, only allows for. However, GUID generation is really, really fast. Really.) The likelihood of collision on any filesystem anywhere on any network is very low. It's safe enough that although it'd be best practice to always check to see if that filename is available anyway, in reality you would never even need to do that.
So you're looking at no I/O operations except the save itself, and <0.2 milliseconds (on a test machine) to generate the name itself. Pretty fast.
You want System.IO.Path.GetTempFileName()
I can't actually say whether it's fastest or not, but it's the right way to do this, which is more important.
You can do something like:
file.MoveTo(deletedfilesdir + @"\" + f.Name + **DateTime.Now.ToFileTimeUtc()** + f.Extension);