Generate unique random string with desired length using GUID
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:
/// Gets a unqiue key based on GUID string hash code.
/// <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.