Home
C#
Random String
Updated Feb 9, 2025
Dot Net Perls
Random strings. In C# we generate random strings with a built-in method. This method, found in System.IO, generates random strings with high quality randomness. It is easy to use.
This problem can be approached in many ways, but the approaches that use the Random class have weaknesses. We can get repeating numbers due to the time-based seed value.
Random
Random Lowercase Letter
Random Paragraphs
Example code. The Path.GetRandomFileName method is an effective way of generating strings. It uses RNGCryptoServiceProvider for better randomness, but is limited to 11 characters.
Part 1 We call the Path.GetRandomFileName method from the System.IO namespace.
Part 2 The string contains one period which is not random. We remove the period in the Replace call.
String Replace
Part 3 We invoke the RandomUtil.GetRandomString method 2 times to test that its output seems random.
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() { // Part 1: use GetRandomFileName. string path = Path.GetRandomFileName(); // Part 2: remove period. path = path.Replace(".", ""); return path; } } class Program { static void Main() { // Part 3: test the random string method. Console.WriteLine(RandomUtil.GetRandomString()); Console.WriteLine(RandomUtil.GetRandomString()); } }
wzp3t2j5a2o ogj0xvz2pak
Cryptographic. GetRandomFileName uses RNGCryptoServiceProvider—this logic is cryptographic-strength. GetBytes 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
So The characters in the strings were filled from the RNGCryptoServiceProvider class in the base class library.
RNGCryptoServiceProvider
Summary. With the Path class, we can obtain 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 9, 2025 (rewrite).
Home
Changes
© 2007-2025 Sam Allen