ShortLink Generator (random gen)

My current coding project is a temporary file store/share web app.
Now days everyone uses free coud services such as dropbox, google drive, and many others, but I remember the days where temp upload and share sites were a thing.
I still think it’s convenient for those that don’t use any cloud storage.
SO, one of the important functions is the shortlink generator. The link you share with your friends to access the temporary file you’ve uploaded.
Here’s the simple c# code I will be using.

The short link will be generated, and from there through DbContext, the app will make sure that the short link is in fact unique. If !unique, re-generate and check again. I highly doubt the app would have to re-generate though… But you always plan for the worst right.

static void Main(string[] args)
{
    // START OF MAIN /////////////////////


    Console.WriteLine(ShortLinkGenerator(6));


    // END OF MAIN /////////////////////
}

public static string ShortLinkGenerator(int length)
{
    Random random = new Random();
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz12345679";
    return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
}

Leave a Reply

Your email address will not be published. Required fields are marked *