Saturday, July 12, 2008

C#: Get A Unique Random String Using GUID Hash Code

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 key returned.</returns>
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);
}

If you find this post helpful, would you buy me a coffee?


3 comments:

  1. this is predictable... so use with caution.. meaning, don't use it for any kind of security. use the random hash generation if you want a secure key.

    ReplyDelete
  2. there is no difference just use Random.Next(length).ToString('x')

    ReplyDelete