问题描述
我已经实现了一个算法,将生成唯一名称的文件,将节省硬盘上。林追加日期时间,小时,分钟,第二和毫秒,但仍然会产生重复的文件名,因为IM一次上传多个文件。什么是生成唯一名称的最佳解决方案对于要存储在硬盘驱动器上的文件,所以2号文件是一样的吗?
I have implemented an algorithm that will generate unique names for files that will save on hard drive. Im appending DateTime,Hours,Minutes,Second and Milliseconds but still it generates duplicate name of files because im uploading multiple files at a time. What is the best solution to generate unique names for files to be stored on hard drive so no 2 files are same?
推荐答案
如果可读性也无所谓,用的GUID。
If readability doesn't matter, use GUIDs.
例如:
var myUniqueFileName = string.Format(@"{0}.txt", Guid.NewGuid());
在我的节目,我有时试图例如10次,产生一个可读的名称(Image1.png..Image10.png),如果失败,我回落到的GUID。
In my programs, I sometimes try e.g. 10 times to generate a readable name ("Image1.png".."Image10.png") and if that fails, I fall back to GUIDs.
更新:
最近,我也用的代替的GUID:
Recently, I've also use DateTime.Now.Ticks
instead of GUIDs:
var myUniqueFileName = string.Format(@"{0}.txt", DateTime.Now.Ticks);
到我的好处是,这会产生一更短和更好看的文件名,相比的GUID。
The benefit to me is that this generates a shorter and "nicer looking" filename, compared to GUIDs.
请注意,在某些情况下(例如,在非常短的时间产生大量的随机名称时),这可能的使非唯一值。
Please note that in some cases (e.g. when generating a lot of random names in a very short time), this might make non-unique values.
坚持的GUID,如果你想真正确保文件名是唯一的,他们转流到其他计算机时也是如此。
Stick to GUIDs if you want to make really sure that the file names are unique, even when transfering them to other computers.
这篇关于如何生成在C#中唯一的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!