Convert a String to a Byte Array?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a string that I received from a web service call and I want to write it to a Stream. I cannot figure out how to access the string as a byte array and write it to the Stream. Any thoughts. I looked at Byte.Parse() but it will only convert a string represntation of a number and convert it to a byte.

Thanks,

Brian
 
ASCIIEncoding.ASCII.GetBytes(string s);

Returns a byte[]


Brian said:
I have a string that I received from a web service call and I want to
write it to a Stream. I cannot figure out how to access the string as a
byte array and write it to the Stream. Any thoughts. I looked at
Byte.Parse() but it will only convert a string represntation of a number and
convert it to a byte.
 
Brian said:
I have a string that I received from a web service call and I want to
write it to a Stream. I cannot figure out how to access the string as
a byte array and write it to the Stream. Any thoughts. I looked at
Byte.Parse() but it will only convert a string represntation of a
number and convert it to a byte.

You need to work out which encoding you need to use, and call GetBytes
on that encoding with the string.

For instance:

byte[] bytes = Encoding.UTF8.GetBytes(...);

Alternatively, create a StreamWriter wrapping the stream, and write the
string to that. Again, you'll need to use the right encoding.

See http://www.pobox.com/~skeet/csharp/unicode.html
 
Back
Top