casting a byte array stored in a string to a byte array

I am being passed a byte array representing a pdf as part of an xml node.

the byte array int the xml looks like this

<Document>
Xh0XQo+PgovVHlwZSAvDAwIG4gCjAwMDAxNTc0MjkgMDAwMDAgbiAKMDAwMDE1ODQ1NSAwMDAwMCBuIAowMDAwMTU5MzY1IDAwMDAwIG4gCjAwMDAxNTk2MjEgMDATg5MyAwMDAwMCBuIAowMDAwMTYwMTQzIDAwMDAwIG4gCjAwMMDE2MDYzNSAwMDAwMCBuIAowMDAwMTYwODk5IDAwMDAwIG4gCjAwMDAxNNTkgMDAwMDAgbiAwMDE2NDkxMiAwMDAwMCBuIAowMDAwMTY1MTwMDAwIG4gCjAwMDAxNjU0MzYgMDAwMDE2NTUyMyAwMDAwMCBuIAowMDAwMTY1NzA5IDAwMDAwIG4gCjAwMDAxNjU5MjcgMDAwMDAgbiAKMDA4MTg3OSAwMDAwMCBuIAowMMTgxOTc4IDAwMDAwIG4gCnRyYWlsZXIKPDwvU2l6ZSAxMTMxCi9Sb290IDEgMCBSCi9JbmZvIDMgMCBSCi9JRCBbPDgyMTQwQURDM0QwOTRCREZBODI2MjM4Q0VBM0YxODA3PiA8ODIxNDBBREMzRDA5NEJERkE4MjYyMzhDRUEzRjE4MDc+XQovRW5jcnlwdCA0IDAgUgo+PgpzdGFydHhyZWYKMTgyMDEzCiUlRU9GCg...........</Document>

So I first copy the bytearray into a string variable .

 string pdfbyte = GetNodeUsingXpath(xpath.....);

Now I would like to cast this pdfbyte into a byte array.

 byte[] output = (byte[])pdfbyte;
 byte[]  output = byte.parse(pdfbyte);

These dont work.

I have looked online but could not find a simple solution to cast a byte array stored in a string variable to a byte array. Any pointers would be helpful.

Basically, I would like to copy the bytearray that is being sent as part of the xml into a byte array variable.

Jon Skeet
people
quotationmark

If you've got binary data within an XML document, I would hope that it's base64-encoded. Text data and binary data are different, and you shouldn't be trying to store arbitrary binary data in a string directly.

If it is, you can just use:

string base64 = GetNodeUsingXpath(xpath.....); 
byte[] output = Convert.FromBase64String(base64);

You may find you need to trim the string first:

byte[] output = Convert.FromBase64String(base64.Trim());

If it's not base64, you'll need to look carefully at what the text looks like. It may be hex instead, although that's not terribly likely. If someone has just use Encoding.GetString(bytes) to start with, then that code will need to be fixed, and it's almost guaranteed to lose data.

EDIT: Now that we can see some of the data, it does indeed look like it's base64.

people

See more on this question at Stackoverflow