tags:

views:

296

answers:

1

Hi, trying to duplicate some PHP code in C#. The PHP code uses the uniqid function with the more entropy parameter set to true. Any idea of how to best duplicate this in C#?

http://us2.php.net/uniqid

+6  A: 

something like:

string uniqid(string prefix, bool more_entropy) {
    if(string.IsNullOrEmpty(prefix)) 
      prefix = string.Empty;

    if (!more_entropy) {
      return (prefix + System.Guid.NewGuid().ToString()).Left(13);
    } else {
      return (prefix + System.Guid.NewGuid().ToString() + System.Guid.NewGuid().ToString()).Left(23);
    }
 }

Edit: To reflect comments

This is a very simple off the top of my head solution, and I'd suggest that for a more rigorous solution you'd investigate proper 'random' number' generation such as via System.Math namespace directly. Please see these other SO questions and answers on random number generation.

System.Guid.NewGuid().ToString()

Will give you a unique string.

Preet Sangha
Thank you so much - thats kind of what I was thinking but I wanted to be sure.
Keep in mind that only the entire Guid is supposed to be almost-certainly unique. That's not necessarily true for a portion of its string representation. See http://blogs.msdn.com/oldnewthing/archive/2008/06/27/8659071.aspx
VolkerK
String.Left() would be String.Substring() in C#
sshow