Home
C#
Random String
This page was last reviewed on Apr 27, 2023.
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
Example code. The Path.GetRandomFileName method here is an effective way of generating strings. It uses RNGCryptoServiceProvider for better randomness.
However It is limited to 11 random characters. This is sometimes not sufficient.
Detail This method invoked the Path.GetRandomFileName method from the System.IO namespace.
Note The string contains one period which is not random. We remove the period in the Replace call.
String Replace
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()); } }
ssrpcgg4b3c addlgsspvhf uqb1idvly03 ikaqowml3te kjfmezehgm4
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
A 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.
Final note. The quality of the random strings is higher than in other methods. It requires less code and may lead to fewer bugs. This is always an advantage.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 27, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.