I am trying to generate a random string in .NET and convert to bytes, and found it a bit difficult. I need a complete set of possible characters, and I understand that a string can contain any character.
My code currently looks like this:
var plainText = new StringBuilder();
for (int j = 0; j < stringLength; ++j)
{
plainText.Append((char)_random.Next(char.MinValue, char.MaxValue));
}
byte[] x = Encoding.Unicode.GetBytes(plainText.ToString());
string result = Encoding.Unicode.GetString(x);
Theoretically, plainTextand resultshould be the same. They are basically the same, but some of the original characters are lost, they seem to be characters in the range 55000-57000 - they are replaced by the symbol 65533.
I assume the problem is related to my encoding, but I thought Unicode would handle this correctly. I tried UTF8 and UTF32, but they give me the same problem.
Any thoughts?
source
share