Eric 的随机文件名 生成方法

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

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

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(charList.ToArray());
}
#endregion





posted @ 2007-06-30 20:57 Eric Fine 阅读(1942) 评论(9)  编辑 收藏 网摘 所属分类: Components & Controls

  回复  引用    
#1楼2007-06-30 22:00 | wyn[未注册用户]
Guid不好吗
  回复  引用  查看    
#2楼2007-06-30 22:26 | Brush      
没考虑过,不知道LZ有没有与一般的方法比较过。
我觉得用 日期文件夹+时间名文件的方法不错的,也比较好查看。

  回复  引用  查看    
#3楼2007-07-01 00:31 | 狂人      
.NET自带 System.IO.Path.GetRandomFileName()
  回复  引用    
#4楼2007-07-02 09:07 | bosswin[未注册用户]
GetRandomFileName()
不太好,扩展名都是乱的。

  回复  引用  查看    
#5楼[楼主]2007-07-02 09:46 | Eric Fine      
System.IO.Path.GetRandomFileName()是通过加密算法生成的8.3文件名, 不但速度比我的方法慢得多,而且生成的文件名也不"友好" -_-
  回复  引用  查看    
#6楼2007-07-02 11:38 | 李一永      
同意!!
  回复  引用  查看    
#7楼2007-07-30 10:15 | Clark Zheng      
mark
  回复  引用    
#8楼2007-07-31 16:22 | PeRL[未注册用户]
谢谢ERIC,您的这个函数帮我解决了一个大问题:)



发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 801560




相关文章:

相关链接: