生成随机字符串

类别:.NET开发 点击:0 评论:0 推荐:

  /// <summary>
  /// 获取随机字符串
  /// </summary>
  /// <param name="strLength">字符串长度</param>
  /// <param name="Seed">随机函数种子值</param>
  /// <returns>指定长度的随机字符串</returns>
  public static string RndString( int strLength, params int[] Seed )
  {
   string strSep = ",";
   char[] chrSep = strSep.ToCharArray();

   //因1与l不容易分清楚,所以去除
   string strChar = "2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z"
    + ",A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,W,X,Y,Z";

   string[] aryChar= strChar.Split( chrSep, strChar.Length );

   string strRandom = string.Empty;
   Random Rnd;
   if( Seed != null && Seed.Length > 0 )
   {
    Rnd = new Random( Seed[0] );
   }
   else
   {
    Rnd = new Random();
   }

   //生成随机字符串
   for( int i=0; i < strLength; i++ )
   {
    strRandom += aryChar[Rnd.Next( aryChar.Length )];
   }

   return strRandom;
  }

本文地址:http://com.8s8s.com/it/it42736.htm