C# Random String

by Sam Allen - Updated January 7, 2010

You want to generate random strings in the C# programming language targeting the .NET Framework. The base class library provides an excellent method in System.IO that generates random strings with the highest quality randomness, and is very easy to use in your code. Here we look at how you can generate random strings using the GetRandomFileName method, which internally uses high-quality random numbers to generate the strings, using the C# language.

Random strings

First, this problem can be approached in many ways, but the approaches that use the Random class have several weaknesses, primarily related to edge cases and repeating numbers due to the time-based seed value of the Random class. For this reason, the Path.GetRandomFileName method here is sometimes superior, because it uses RNGCryptoServiceProvider for better randomness. However, it is limited to 11 random characters.

--- Program that generates random strings (C#) ---

using System;
using System.IO;

/// <summary>
/// Random string generators.
/// </summary>
static class RandomUtil
{
    /// <summary>
    /// Get random string of 11 characters.
    /// </summary>
    /// <returns>Random string.</returns>
    public static string GetRandomString()
    {
        string path = Path.GetRandomFileName();
        path = path.Replace(".", ""); // Remove period.
        return path;
    }
}
class Program
{
    static void Main()
    {
        // Test the random string method.
        Console.WriteLine(RandomUtil.GetRandomString());
        Console.WriteLine(RandomUtil.GetRandomString());
        Console.WriteLine(RandomUtil.GetRandomString());
        Console.WriteLine(RandomUtil.GetRandomString());
        Console.WriteLine(RandomUtil.GetRandomString());
    }
}

--- Output of the program ---

ssrpcgg4b3c
addlgsspvhf
uqb1idvly03
ikaqowml3te
kjfmezehgm4

GetRandomString method implementation. In the program text above, two classes are defined, the first being a utility static class, and the second being the Program class with the Main entry point. The GetRandomString method invoked the Path.GetRandomFileName method from the System.IO namespace. It is a parameterless static method, and returns a random string containing 12 characters. The string contains one period which is not random; we remove the period in the Replace call.

Testing the random strings. The Main entry point in the program text calls the GetRandomString method five times and prints the results to the screen. You can see the five strings are completely random. The characters in the strings were filled from the RNGCryptoServiceProvider class in the base class library.

Cryptographic strength

The RNGCryptoServiceProvider class that the GetRandomFileName method is implemented with is cryptographic-strength. The GetBytes method is invoked internally and it returns random bytes. These random bytes are then used with bitwise ANDs to fill the result value. You can find more about this method on the site.

(See Path.GetRandomFileName Method.)

Summary

Here we looked at how you can obtain a random string using the System.IO namespace in the C# programming language. This method has a limitation on the length of the result, which means you may need to call it more than once or truncate the result. The quality of the random strings is higher than in methods that do not use cryptographic random numbers. Additionally, it requires less code and may lead to fewer bugs.

(Do not copy this page.)

Dot Net Perls | Search
Strings | Environment.NewLine | IndexOf String Examples | Replace String Examples | Split String Examples | Substring Programs
C# | Integer.TryParse | ArrayList Examples | Bituminous Coal | Sleep Method Use
© 2009 Sam Allen. All rights reserved.
Dot Net Perls | Sam Allen