ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

RandomString

Return a random string of a chosen length

Source

public static class StringHelper
{
    public static string RandomString( int length )
    {
        Random random = new Random((int) DateTime.Now.Ticks);
        StringBuilder sb = new StringBuilder();

        string validChars = "abcdefghijklmnopqrstuvwxyz0123456789";
        char c;
        for ( int i = 0; i < length; i++ )
        {
            c = validChars[random.Next(0, validChars.Length)];
            sb.Append(c);
        }

        return sb.ToString();
    }
}

Example

StringHelper.RandomString(16)

Author: Stuart Sillitoe

Submitted on: 8 jul. 2016

Language: C#

Type: String

Views: 4739