Random String Generator in C#

produce random string simply in .net, without special characters if need be

It is very simple to get random string since the introduction of Membership.GeneratePassword() - so this really just a way to utilize that and pull out special characters if that is what you are looking for.
public static string ToRandomString(this string s, 
    int length, bool isOnlyAlphaNumeric = true, 
    int minSpecialCharacters = 1)
{
    if (isOnlyAlphaNumeric) minSpecialCharacters = 0;
    s = Membership
        .GeneratePassword(length, minSpecialCharacters);
    if (!isOnlyAlphaNumeric) return s;
            
    char[] msSpecialCharacters = 
        "!@#$%^&*()_-+=[{]};:<>|./?".ToCharArray();
    string filler = 
        Membership.GeneratePassword(length, 0);
    int fillerIndex = 0;
    int fillerBuffer = 0;

    while(s.IndexOfAny(msSpecialCharacters) > -1 
        || s.Length < length)
    {
        s = s.RemoveCharacters(msSpecialCharacters);
        fillerBuffer =length - s.Length;
        if((fillerBuffer + fillerIndex) > filler.Length)
        {   // filler would out-of-bounds, get a new one
            filler = 
                Membership.GeneratePassword(length, 0);
            fillerIndex = 0;
        }
        s += filler.Substring(fillerIndex, fillerBuffer);
        fillerIndex += fillerBuffer;
    }
    return s;
}

public static string RemoveCharacters
    (this string s, char[] characters)
{
    return new string(s.ToCharArray()
        .Where(c => !characters.Contains(c)).ToArray());
}

This has been added to my Naspinski.Utilities library, though it isn't released just yet, looking to tweak it a bit first.

Add comment

Loading