.NET Short Unique Identifier

前端 未结 23 1153
忘掉有多难
忘掉有多难 2020-12-07 11:27

I need a unique identifier in .NET (cannot use GUID as it is too long for this case).

Do people think that the algorithm used here is a good candidate or do you have

23条回答
  •  鱼传尺愫
    2020-12-07 12:05

    Here's my small method to generate a random and short unique id. Uses a cryptographic rng for secure random number generation. Add whatever characters you need to the chars string.

    private string GenerateRandomId(int length)
    {
        char[] stringChars = new char[length];
        byte[] randomBytes = new byte[length];
        using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
        {
            rng.GetBytes(randomBytes);
        }
    
        string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";           
    
        for (int i = 0; i < stringChars.Length; i++)
        {
            stringChars[i] = chars[randomBytes[i] % chars.Length];
        }
    
        return new string(stringChars);
    }
    

提交回复
热议问题