2022-02-06 02:06:25 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
2022-02-06 04:17:08 +00:00
|
|
|
|
public class RandomString
|
|
|
|
|
{
|
|
|
|
|
// Generates a random string with a given size.
|
|
|
|
|
public static string Generate(int size)
|
|
|
|
|
{
|
|
|
|
|
var builder = new StringBuilder(size);
|
2022-02-06 02:06:25 +00:00
|
|
|
|
|
2022-02-25 02:36:46 +00:00
|
|
|
|
var random = new Random();
|
2022-02-06 02:06:25 +00:00
|
|
|
|
|
2022-02-06 04:17:08 +00:00
|
|
|
|
// Unicode/ASCII Letters are divided into two blocks
|
|
|
|
|
// (Letters 65–90 / 97–122):
|
|
|
|
|
// The first group containing the uppercase letters and
|
|
|
|
|
// the second group containing the lowercase.
|
2022-02-06 02:06:25 +00:00
|
|
|
|
|
2022-02-06 04:17:08 +00:00
|
|
|
|
// char is a single Unicode character
|
2022-02-25 02:36:46 +00:00
|
|
|
|
var offsetLowerCase = 'a';
|
|
|
|
|
var offsetUpperCase = 'A';
|
2022-02-06 04:17:08 +00:00
|
|
|
|
const int lettersOffset = 26; // A...Z or a..z: length=26
|
2022-02-06 02:06:25 +00:00
|
|
|
|
|
2022-02-06 04:17:08 +00:00
|
|
|
|
for (var i = 0; i < size; i++)
|
|
|
|
|
{
|
|
|
|
|
char offset;
|
|
|
|
|
if (random.Next(0, 2) == 0)
|
|
|
|
|
{
|
|
|
|
|
offset = offsetLowerCase;
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
offset = offsetUpperCase;
|
|
|
|
|
}
|
2022-02-06 02:06:25 +00:00
|
|
|
|
|
2022-02-06 04:17:08 +00:00
|
|
|
|
var @char = (char)random.Next(offset, offset + lettersOffset);
|
|
|
|
|
builder.Append(@char);
|
|
|
|
|
}
|
2022-02-06 02:06:25 +00:00
|
|
|
|
|
2022-02-06 04:17:08 +00:00
|
|
|
|
return builder.ToString();
|
|
|
|
|
}
|
2022-02-06 02:06:25 +00:00
|
|
|
|
}
|