Sri Reddy
Sri Reddy

Reputation: 7012

Store binary data string into byte array using c#

I have a webservice that returns a binary data as a string. Using C# code how can I store it in byte array? Is this the right way?

System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(inputString);

Actually, this didn't work. Let me explain it more: the web service code converts a string (containing XSLFO data) into byte array using utf8 encoding. In my web service response I only see data something like "PGZvOnJvb3QgeG1sbnM6Zm89Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvWFNML0Zvcm1hdCIgeG1sbnM­6eGY9Imh0dHA6Ly93d3cuZWNyaW9uLmNvbS94Zi8xLjAiIHhtbG5zOm1zeHNsPSJ1c==". Actually I would like to have the original string value that was converted into byte[] in the service. Not sure if it possible?

Upvotes: 0

Views: 10251

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502696

No, that's a bad idea.

Unless the input data was originally text, trying to use Encoding is a bad idea. The web service should be using something like base64 to encode it - at which point you can use Convert.FromBase64String to get the original binary data back.

Basically, treating arbitrary binary data as if it were encoded text is a quick way to lose data. When you need to represent binary data in a string, you should use base64, hex or something similar.

This may mean you need to change the web service as well, of course - if it's creating the string by simply treating the binary data as UTF-8-encoded text, it's broken to start with.

Upvotes: 12

Chad
Chad

Reputation: 19619

If the string is encoded in UTF8 Encoding, then yes that is the correct way. If it is in Unicode it is very similar:

System.Text.Unicode encoding = new System.Text.Unicode();
byte[] bytes = encoding.GetBytes(inputString);

Base64Encoding is a little different:

byte[] bytes = Convert.FromBase64String(inputString);

Upvotes: 0

Related Questions