利用 当前时间与2000-1-1 0:0:0 相差的毫秒数转成36进制字符串 加上4位随机字符串 生成一个随机文件名. 算是长度比较短而唯一性比较高的随机文件名生成方法了
private static string charDictionary = "0123456789abcdefghijklmnopqrstuvwxyz";
public static string GetRandomString(int length)
...{
return GetRandomString(new Random(), length);
}
public static string GetRandomString(string dictionary, int length)
...{
return GetRandomString(new Random(), dictionary, length);
}
public static string GetRandomString(Random r, int length)
...{
return GetRandomString(r, charDictionary, length);
}
public static string GetRandomString(Random r, string dictionary, int length)
...{
if(r == null)
...{
r = new Random();
}
StringBuilder sb = new StringBuilder();
char[] chars = dictionary.ToCharArray();
for(int i = 0; i < length; i++)
...{
sb.Append(chars[r.Next(0, chars.Length)]);
}
return sb.ToString();
}
public static string GetRandomFileName()
...{
return GetRandomFileName(new Random());
}
public static string GetRandomFileName(Random r)
...{
string fileName = ConvertToRadix(GetTimeSpan("f"), 36);
fileName += GetRandomString(r, 4);
return fileName.ToLower();
}
internal static long GetTimeSpan(string dateTimePart)
...{
long now = DateTime.Now.Ticks;
long begin = DateTime.Parse("2000-1-1 0:0:0").Ticks;
long timeSpan = now - begin;
switch(dateTimePart.ToLower())
...{
case "f":
timeSpan = timeSpan / TimeSpan.TicksPerMillisecond;
break;
case "s":
timeSpan = timeSpan / TimeSpan.TicksPerSecond;
break;
case "m":
timeSpan = timeSpan / TimeSpan.TicksPerMinute;
break;
case "h":
timeSpan = timeSpan / TimeSpan.TicksPerHour;
break;
case "d":
timeSpan = timeSpan / TimeSpan.TicksPerDay;
break;
default:
timeSpan = 0;
break;
}
return timeSpan;
}
public static string ConvertToRadix(long number, byte scale)
...{
if(scale < 2 || scale > 36)
...{
throw new Exception("Scale number must not be less than 2 and bigger then 36.");
}
char[] dictionary = charDictionary.ToCharArray()
List<char> charList = new List<char>();
long positive = Math.Abs(number);
for(int i = 0; i < 64; i++)
...{
if(positive == 0)
...{
break;
}
charList.Add(dictionary[positive % scale]);
positive /= scale;
}
charList.Reverse();
return new string(charList.ToArray());
}

本文介绍了一种生成短且高度唯一的随机文件名的方法:利用当前时间与基准时间的毫秒差转为36进制,并附加4位随机字符串。这种方法能够确保文件名的唯一性,同时保持较短的长度。
200

被折叠的 条评论
为什么被折叠?



