TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Random String

This C# example shows how to generate random strings using the GetRandomFileName method.

Random strings are sometimes needed.

We generate them with a built-in method on the Path type. This method, found in System.IO, generates random strings with high quality randomness. It is easy to use.

Example. First, this problem can be approached in many ways, but the approaches that use the Random class have weaknesses. These are primarily related to edge cases and repeating numbers due to the time-based seed value of the Random class.

Thus: The Path.GetRandomFileName method here is sometimes superior. It uses RNGCryptoServiceProvider for better randomness.

However: It is limited to 11 random characters. This is sometimes not sufficient.

C# program that generates random strings

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

ssrpcgg4b3c
addlgsspvhf
uqb1idvly03
ikaqowml3te
kjfmezehgm4

In this example, 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.

Note: The string contains one period which is not random. We remove the period in the Replace call.

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

RNGCryptoServiceProvider

Cryptographic. The RNGCryptoServiceProvider class that the GetRandomFileName method is implemented with is cryptographic-strength. The GetBytes method is invoked internally and it returns random bytes.

And: These random bytes are then used with bitwise ANDs to fill the result value.

Path.GetRandomFileName

Summary. We obtained a random string. 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 other methods.

And: It requires less code and may lead to fewer bugs. This is always an advantage.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf