Just trying to get the PermanentUserKey to work on my USBizi device (FW Ver 4.1.8.0) and am creating some stub test code…
Having some real problems with the following code:
Guid g = Guid.NewGuid();
byte[] b = new byte[Configuration.PermanentUserKey.KeyLength];
b = g.ToByteArray();
char[] c = new char[Configuration.PermanentUserKey.KeyLength];
c = Encoding.UTF8.GetChars(b);
string s = new string(c);
return s;
No matter what I do I get a “Exception was thrown: System.Exception” on the line “c = Encoding.UTF8.GetChars(b);”
Not all elements of your byte array result in printable characters. A GUID is a series of numbers, and ToByteArray returns the byte values of the numbers, not the printable characters that represent them. Notice that a GUID has 32 characters, while Guid.ToByteArray results in a byte array of 16 elements.
Also note:
Guid g = Guid.NewGuid();
byte[] b = new byte[Configuration.PermanentUserKey.KeyLength];
b = g.ToByteArray();
char[] c = new char[Configuration.PermanentUserKey.KeyLength];
c = Encoding.UTF8.GetChars(b);
string s = new string(c);
return s;
It is unnecessary to initialize b on the second line, and c on the fourth line, as neither Guid.ToByteArray() nor Encoding.UTF8.GetChars() copies the result into your array, but rather returns a new array.
I had completely forgotten that the numbers were byte values and not actual characters! Too many late nights working on my project.
I knew I didn’t need to initialize on each line separately but when I was trying to find the cause of the problem I always separate out compound statements to find out which bit I have broken.