In a previous article, I mentioned how to Generate Random Number in C# but in this article, I have mentioned how to generate random alphanumeric strings in C# using various possible methods.

The random string means a series of numbers, letters and alphanumeric strings that have no pattern, these strings can be helpful in generating random passwords, security code etc.

In C# Random class can be used to generate a random numbers using methods like Random.Next() or Random.NextSingle() or Randome.NextDouble() etc. So using the Random class, we can generate a new set of alphanumeric random numbers.

Let's take a look at various possible ways to generate randome alphanumeric string in C#.

Using All characters generate alphanumeric string

In this example, we will create string of all characters and numbers and then we will pick a alphabet or number randomly to create a string or 8 characters.

using System;

namespace RandomAlphaNumericString
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var stringChars = new char[8];
            var random = new Random();

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

            var randomStr = new String(stringChars);
            Console.WriteLine(randomStr);

        }
    }
}

Output:

tms1IBmG

As you can see from the above code, we are adding a new character in char array, randomly picking it from all alphabets (chars) and then converting the char array to a string, which generates random alphanumeric 8 characters string.

Using Linq

Considering the above example, instead of looping and storing each character in an array we can also use Linq directly to skip "for" loop and generate an alphanumeric random string more quickly in C#.

using System;
using System.Linq;

namespace RandomAlphaNumericString
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            var length = 8;
            var random = new Random();

            var randomStr = new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
            Console.WriteLine(randomStr);
        }
    }
}

Output:

9aZcvZPy

generate-random-alphanumeric-string-csharp

Using .NET Core RNGCryptoServiceProvider 

RNGCryptoServiceProvider creates a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP), so we can use it to generate random alphanumeric string in C#.

using System;
using System.Security.Cryptography;
using System.Text;

namespace RandomAlphaNumericString
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            byte[] data = new byte[12];
            using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
            {
                crypto.GetBytes(data);
            }

            StringBuilder result = new StringBuilder(12);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            Console.WriteLine(result.ToString());
        }
    }
}

Output:

HTDhITJpFtL2

Using Path.RandomFileName

We can also use Path.GetRandomFileName, which always returns a 12 character string with a period at the 9th character. So you'll need to strip the period (since that's not random) and then take 8 characters from the string. 

using System;
using System.IO;

namespace RandomAlphaNumericString
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string path = Path.GetRandomFileName();
            path = path.Replace(".", ""); // Remove period.
            var randomStr = path.Substring(0, 8);  // Return 8 character string
            Console.WriteLine(randomStr);
        }
    }
}

output:

ayk02gcd

That's it, hope you can use any of the above solution to generate random alphanumeric string in C#, I will recommend using linq approach or first method, as those 2 are the fastest and easiest too.

You may also like to read:

How to get file extension or file size in C# ? ( Code With Example )

Read OR Write OR Modify Web.Config file using C#

LINQ to Entities does not recognize the method 'System.DateTime Parse(System.String)' method

how to convert UTC DateTime to local datetime in C#?

There is already an open datareader associated - error in C#

How to rename a file and directory in C#?

Compare System Time with database time only (not datetime)

How to create dynamic list type in C#?

Convert PDF to Image in C# (Console Application Example)