In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Generate unique random string with desired length using GUID

No comments

GUID, also known as Globally Unique Identifier, is an 128-bit integer (16 bytes) that can be used to uniquely identify a record in the database (other than the auto-increase number). It is best used as a primary key as well.
But in some occasion, what you need is not really a GUID, but a random string that is "unique enough" to be used by your system. And you might want to store it as a string in your database (for whatever reason).
In C#, you can do this by using the GUID hash code. Here is the function that returns a "unique enough" string with a desired length:

        /// <summary>         
        /// Gets a unqiue key based on GUID string hash code.
        /// </summary>
         /// <param name="length">The length of the key returned.</param>
         /// <returns>Unique string</returns>
         private static string GetUniqueString(int length)
         {
             StringBuilder uniqHashKey = new StringBuilder();
             while (uniqHashKey.Length < length)
             {
                 // Get the GUID.
                 uniqHashKey.Append(Guid.NewGuid().ToString().GetHashCode().ToString("x"));
             }
             return uniqHashKey.ToString();
         }

No comments :