随机文件名生成方法

利用 当前时间与2000-1-1 0:0:0 相差的毫秒数转成36进制字符串 加上4位随机字符串 生成一个随机文件名. 算是长度比较短而唯一性比较高的随机文件名生成方法了.

实测1,000,000 * 100次, 平均每生成1,000,000个随机文件名耗时0.3秒. (测试平台:Dell 640M, T2300, XPSP2)

<script type="text/javascript">google_ad_client = "pub-2048279401139630";google_ad_slot = "8856771542";google_ad_width = 728;google_ad_height = 90;document.write("<s"+"cript type='text/javascript' s"+"rc='http://pagead2.googlesyndication.com/pagead/show_ads"+"."+"js'></scr"+"ipt>");</script>
private static string charDictionary = "0123456789abcdefghijklmnopqrstuvwxyz";

#region GetRandomString
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();
}
#endregion

#region GetRandomFileName
public static string GetRandomFileName()
{
    
return GetRandomFileName(new Random());
}

public static string GetRandomFileName(Random r)
{
    
long timeSpan = (long)(DateTime.Now - new DateTime(200011)).TotalMilliseconds;
    
string fileName = ConvertToRadix(timeSpan, 36);
    fileName 
+= GetRandomString(r, 4);
    
return fileName.ToLower();
}
#endregion

#region ConvertToRadix
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");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值