It’s easy enough to use System.Text.UnicodeEncoding.Unicode.GetBytes() to do this kind of conversion but problems could occur when you have invisible/control characters in the string. A better approach would be to first convert the string to a character array then to byte array:
private static byte[] StringToBytes(string str)
{
Converter conv = new Converter((c) => (byte)c);
Array.ConvertAll(str.ToCharArray(), conv);
}
分類: .NET Stuff