在保存文件,创建目录时,为了保证名称不重复,经常使用Random产生一个随机数,有更简单且不会重复的办法是:
Guid.NewGuid().ToString()
就会生成一个类似
37c1acec-4997-475b-9145-8d83706554e6
的字符串 且这个字符串是独一无二的。
GUID有如下用法:
static void Main(string[] args)
{ var uuid = Guid.NewGuid().ToString();
Console.WriteLine("Guid.NewGuid().ToString():"+uuid);
var uuidN = Guid.NewGuid().ToString("N");
Console.WriteLine("Guid.NewGuid().ToString(\"N\"):" + uuidN);
var uuidD = Guid.NewGuid().ToString("D");
Console.WriteLine("Guid.NewGuid().ToString(\"D\"):" + uuidD);
var uuidB = Guid.NewGuid().ToString("B");
Console.WriteLine("Guid.NewGuid().ToString(\"B\"):" + uuidB);
var uuidP = Guid.NewGuid().ToString("P");
Console.WriteLine("Guid.NewGuid().ToString(\"P\"):" + uuidP);
var uuidX = Guid.NewGuid().ToString("X");
Console.WriteLine("Guid.NewGuid().ToString(\"X\"):" + uuidX);
}
输出结果:
Guid.NewGuid().ToString():ace565e6-0ec8-4e96-b8e0-293a66b86cfe
Guid.NewGuid().ToString("N"):c5bd28d0b8c1446fb7ea7c8d52596514
Guid.NewGuid().ToString("D"):70c795f4-f0ce-4672-b896-8cb7ea2f3076
Guid.NewGuid().ToString("B"):{1059c544-6278-430f-ae14-a36699ee70c1}
Guid.NewGuid().ToString("P"):(c56c03d0-dc53-4ee9-85f0-676d018e3502)
Guid.NewGuid().ToString("X"):{0xd300d8bd,0x9bc7,0x4fd6,{0x93,0xe4,0xe6,0x53,0x77,0x10,0xa0,0x70}}