Generating Random Strings in C#: From Beginner to Pro

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How I got tired of googling "random alphanumeric string C#" and wrote this article

\n\n

Admit it honestly: when you needed to generate a random activation code, temporary password, or unique session identifier again, did you just copy the first answer from Stack Overflow? I did that too. But the problem is that generating random alphanumeric strings in C# is not one task, but a whole spectrum of scenarios. And what works for a test token can fail a security audit in production.

\n\n

In this article, we will cover all popular approaches to generating random strings in C#. From naive solutions with Random to cryptographically secure methods approved by OWASP. You will learn which method to choose for passwords, which for URL short links, and which is better to forget altogether. Let's go!

\n\n

1. The simplest way: Random + StringBuilder (but there's a catch)

\n\n

When I was just starting out, my first solution was this code:

\n\n
public static string GenerateRandomString(int length)\n{\n    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";\n    var random = new Random();\n    var result = new StringBuilder(length);\n    \n    for (int i = 0; i < length; i++)\n    {\n        result.Append(chars[random.Next(chars.Length)]);\n    }\n    \n    return result.ToString();\n}
\n\n

Looks logical, right? Take an alphabet, pick a random index, build a string. But this method has two serious problems:

\n\n
    \n
  • Unsafe Random — the Random class is not cryptographically secure. If an attacker finds out the time the object was created (which is easy), they can predict the entire sequence.
  • \n
  • Multithreading issue — if two threads call new Random() with the same seed simultaneously (which often happens with fast sequential calls), they will get identical strings.
  • \n
\n\n

When to use: Only for local tests, generating file names, or debug data. Never for passwords, tokens, or encryption keys.

\n\n

Improved version: static Random

\n\n
private static readonly Random _random = new Random();\n\npublic static string GenerateRandomString(int length)\n{\n    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";\n    var result = new char[length];\n    \n    lock (_random)\n    {\n        for (int i = 0; i < length; i++)\n        {\n            result[i] = chars[_random.Next(chars.Length)];\n        }\n    }\n    \n    return new string(result);\n}
\n\n

We added a lock for thread safety and replaced StringBuilder with a char array — this is faster. But the predictability problem remains.

\n\n

2. Guid.NewGuid(): random string in one line of code

\n\n

When I first saw this trick, I thought: "Brilliant!"

\n\n
string randomString = Guid.NewGuid().ToString("N").Substring(0, 8);
\n\n

Guid generates a 128-bit value that is almost guaranteed to be unique. The "N" method removes hyphens. Substring truncates to the desired length.

\n\n

Pros:

\n
    \n
  • Very short code
  • \n
  • No need to worry about an alphabet
  • \n
  • High speed
  • \n
\n\n

Cons:

\n
    \n
  • Guid contains only hexadecimal characters (0-9, a-f) — an alphabet of only 16 characters
  • \n
  • Not all Guid versions are truly random (version 1 is based on time and MAC address)
  • \n
  • Not suitable for cryptography — the Guid structure is predictable
  • \n
\n\n

When to use: For generating unique identifiers for database records or temporary file names. Not for passwords.

\n\n

3. Path.GetRandomFileName(): random file name

\n\n

Few people know, but .NET already has a built-in random file name generator:

\n\n
<                

Blogs

Book Recommendations