A short while I was engaged in a little project where I had to interact with a third party service provider who required a (30 length) unique id as part of the transaction. I am little dumb and am used to GUIDs for a long time when it comes to unique ids. But GUIDs are more than 30 in length. I was trying out some stupid ways like stripping out the trail part of the GUID to make 30 length unique but my intuition wasn't convinced about the tricks I was working out.
Finally, Sriram helped me with it. I am sharing his code for the benefit of others.
string GenerateUniqueId(int length) { string asciiChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; char[] chars = asciiChars.ToCharArray(); byte[] randombytes = new byte[length]; RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider(); crypto.GetNonZeroBytes(randombytes); StringBuilder result = new StringBuilder(length); foreach (byte b in randombytes) { result.Append(chars[b % asciiChars.Length]); } return result.ToString(); }
Thanks Sriram.
Comments