C# String Examples
C# Basic
C# Data Type
C# OOP
C# IO
C# Graphics & UI
C# Advanced
To generate random alphanumeric strings in C#, you can use the Random
class along with a string containing all the possible characters you want to include. Here's an example that generates a random string of length 10:
using System; using System.Linq; class Program { static void Main() { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random(); var result = new string( Enumerable.Repeat(chars, 10) .Select(s => s[random.Next(s.Length)]) .ToArray()); Console.WriteLine(result); } }
To generate secure random alphanumeric strings, you should use the RNGCryptoServiceProvider
class from the System.Security.Cryptography
namespace. Here's an example that generates a secure random string of length 10:
using System; using System.Linq; using System.Security.Cryptography; class Program { static void Main() { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new RNGCryptoServiceProvider(); var result = new string( Enumerable.Range(1, 10) .Select(_ => { var bytes = new byte[1]; random.GetBytes(bytes); var charIndex = (bytes[0] % chars.Length); return chars[charIndex]; }) .ToArray()); Console.WriteLine(result); } }
Note that the RNGCryptoServiceProvider
class is slower than the Random
class, but provides much stronger security guarantees.
Generate random string in C#:
using System; class Program { static void Main() { string randomString = GenerateRandomString(10); Console.WriteLine(randomString); } static string GenerateRandomString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } }
Random string generation using Guid in C#:
string randomString = Guid.NewGuid().ToString("N").Substring(0, 10);
Random string with uppercase and lowercase characters in C#:
string randomString = Path.GetRandomFileName().Replace(".", "").Substring(0, 10);
Random string with numbers in C#:
string randomString = Guid.NewGuid().ToString("N").Substring(0, 10);
C# random string with special characters:
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_+=<>?"; string randomString = new string(Enumerable.Repeat(chars, 10) .Select(s => s[random.Next(s.Length)]).ToArray());