Random
stringsIn 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.
The Path.GetRandomFileName
method is an effective way of generating strings. It uses RNGCryptoServiceProvider
for better randomness, but is limited to 11 characters.
Path.GetRandomFileName
method from the System.IO
namespace.string
contains one period which is not random. We remove the period in the Replace
call.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
GetRandomFileName
uses RNGCryptoServiceProvider
—this logic is cryptographic-strength. GetBytes
is invoked internally and it returns random bytes.
RNGCryptoServiceProvider
class
in the base class library.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.