1

I have to append a unique code as a querystring, for every url generated. So, the option I chose is to shorten a guid (found here on SO).

public static string CreateGuid()
        {          

          Guid guid = Guid.NewGuid();
            return Convert.ToBase64String(guid.ToByteArray());
        }

Will this be as unique as a guid, cause I have several urls to generate and this guid will be saved in DB.

sukesh
  • 2,379
  • 12
  • 56
  • 111
  • possible duplicate of [guid to base64, for URL](http://stackoverflow.com/questions/1032376/guid-to-base64-for-url) – Fredou Sep 10 '14 at 15:49

2 Answers2

2

Yup, the default string representation of a guid is base16. By reformatting the same value as base64, you get a shorter (but possibly uglier) string.

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
1

You should watch out if you are using this in the url. While the string will be shorter, it will potentially have characters that are illegal in urls, so you may need to run it past

HttpUtility.UrlEncode()

to be safe. Of course, once you do that, it will get a little longer again.

Edit:

Your comment makes it seem like you want some sort of math, so here goes:

Let's assume that you have 24 alphanumeric characters all the time, and casing does not matter. That means each character can be 0-9 + a-z or 36 possibilities. That makes it 24 ^ 36 different possible strings. Refer to this website then:

http://davidjohnstone.net/pages/hash-collision-probability

Which lets you plug in possible values and the number of times you will need to run your code. 24^36 is equivalent to 2^100 (I arrived at this number after some googling, may be incorrect). plugging in 100 into the "number of bits in your hash" field at the link above means if you run your code 1000000 times, you will still only have 3.944300×10^19 odds of a collision, or the same value coming up twice. That's miniscule, but you may run into issues if you are writing something that will be used many many more times than that.

welegan
  • 3,013
  • 3
  • 15
  • 20
  • I'm thinking of just removing any non-alphanumerics or replacing them with any letter. The only concern is, will I still have unique short guids – sukesh Sep 10 '14 at 15:11