Generate random string in C#

Visual Studio C#

Generate a random string of random characters in C#

Here's a simple example of how to generate a random string of a specified length:

using System;
using System.Text;

class Program
{
    static void Main()
    {
        int length = 10;
        string randomString = GenerateRandomString(length);
        Console.WriteLine(randomString);
    }

    static string GenerateRandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder randomString = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++)
        {
            randomString.Append(chars[random.Next(chars.Length)]);
        }

        return randomString.ToString();
    }
}
Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • .Net 4.6
  • Windows 11
  • Visual Studio 2022