C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
GetRandomString: 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.
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
And: These random bytes are then used with bitwise ANDs to fill the result value.
Path.GetRandomFileNameSo: The characters in the strings were filled from the RNGCryptoServiceProvider class in the base class library.
RNGCryptoServiceProviderAnd: It requires less code and may lead to fewer bugs. This is always an advantage.