Where am I going wrong?

Hi,

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);”

What have I missed? What am I doing wrong?

Thanks in advance,

Andy

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 don’t have hardware on me to test. What does the progression of your GUID to Byte to Char look like?

Your first byte in b is actually decimal 180. I don’t think this is a valid UTF-8 character and GetChars is barfing at it.

have you tried just using g.ToString() and make the object to the work for you ?

1 Like

Hi guys,

Many thanks for the responses.

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.

Many thanks again,

Andy