Skip to main content

Generate a short, unique ID in C#. It uses a cryptographically strong random number generator and Base64Url encoding to create a short, URL-safe string. You can adjust the length as needed.

using System;
using System.Security.Cryptography;

public static class ShortIdGenerator
{
    public static string Generate(int length = 12)
    {
        var byteLength = (int)Math.Ceiling(length * 0.75); // Base64 expands by 4/3
        var bytes = new byte[byteLength];
        RandomNumberGenerator.Fill(bytes);

        var base64 = Convert.ToBase64String(bytes)
            .Replace("+", "-")
            .Replace("/", "_")
            .Replace("=", "");

        return base64.Substring(0, length);
    }
}