Unique random string generation

2019-01-03 11:49发布

I'd like to generate random unique strings like the ones being generated by MSDN library:

http://msdn.microsoft.com/en-us/library/t9zk6eay.aspx, for example. A string like 't9zk6eay' should be generated.

标签: c# random
13条回答
小情绪 Triste *
2楼-- · 2019-01-03 12:47

Get Unique Key using GUID Hash code

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);
}
查看更多
登录 后发表回答