May 8, 2021

[Tips] Random string generators C#

Testing 2 different Random string generators.

void Main()
{
 for(int i=0;i<10;i++){
  Console.WriteLine("GetRandomString: " + GetRandomString(8));
 }
 for(int i=0;i<10;i++){
  Console.WriteLine("GetRandomFileName: " + GetRandomFileName());
 } 
}

public static string GetRandomString(int length)
{
    Random random = new Random();
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    return new string(Enumerable.Repeat(chars, length)
      .Select(s => s[random.Next(s.Length)]).ToArray());
}

public static string GetRandomFileName()
{
    string path = Path.GetRandomFileName();
    path = path.Replace(".", ""); // Remove period.
    return path;
}

Result
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomFileName: smb1u03pvyf
GetRandomFileName: 2ccre5kihis
GetRandomFileName: 24thz5is1pj
GetRandomFileName: ni0z42lexag
GetRandomFileName: 1u11tcvd3qv
GetRandomFileName: vtiqp2sevwy
GetRandomFileName: y2jhumy1hcx
GetRandomFileName: 5o0gsyronpk
GetRandomFileName: m0zva3mhdfn
GetRandomFileName: 2a2dzcdkpbl