我希望生成类似于MSDN库(Error Object)创建的随机唯一字符串,例如't9zk6eay'。
这个问题已经被针对各种语言提出过。这里有一个关于密码的问题,同样适用于这里。
如果你想要将字符串用于URL缩短,你还需要使用Dictionary<>或数据库检查以查看生成的ID是否已经被使用过。
public static string GetUniqueKey(int length)
{
string guidResult = string.Empty;
while (guidResult.Length < length)
{
// Get the GUID.
guidResult += Guid.NewGuid().ToString().GetHashCode().ToString("x");
}
// Make sure length is valid.
if (length <= 0 || length > guidResult.Length)
throw new ArgumentException("Length must be between 1 and " + guidResult.Length);
// Return the first length bytes.
return guidResult.Substring(0, length);
}
string randoms = Guid.NewGuid().ToString().Replace("-", string.Empty).Replace("+", string.Empty).Substring(0, 4);
更多相关信息请参见此处。 - Shaiju T