How to convert String into byte[]? -good old C days, where are you?

  • Thread starter Thread starter faustino Dina
  • Start date Start date
F

faustino Dina

Hi,

I'm trying to send a POST request by using HttpWebRequest. To send the data
I should get a Stream:

HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(aUrl);
Stream reqData = wReq.GetRequestStream();

but for writing into the Stream
reqData.Write(?)
the Stream expects a byte[] but my data is in a String field. How to convert
my String into byte[]?

Thanks in advance
 
faustino Dina said:
HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(aUrl);
Stream reqData = wReq.GetRequestStream();

but for writing into the Stream
reqData.Write(?)
the Stream expects a byte[] but my data is in a String field. How to
convert my String into byte[]?

check your help for System.Text.Encoding.UTF8.GetBytes( ).... it takes a
string and returns a byte[]. There are other encodings besides UTF8, but
IMHO that's the best one to use for general use.

-mdb
 
"System.Text.ASCIIEncoding.ASCII.GetBytes(string)" will cut it.

- Noah Coad -
Microsoft MVP
 
As others suggested, you can use System.Text.Encoding to convert your
strings to bytes, but you will soon become tired of converting strings to
bytes every time you need to do some I/O with them.

So, the solution is to wrap the stream with a StreamWriter:

StreamWriter writer = new StreamWriter(wReq.GetRequestStream());
writer.WriteLine("hello world!").

By default, the StreamWriter will use UTF8 encoding, but if you want a
different encoding, you can take a look at the StreamWriter constructors.

Also, if you need to read strings from a Stream, wrap it with a
StreamReader.

Bruno.
 
Noah Coad said:
"System.Text.ASCIIEncoding.ASCII.GetBytes(string)" will cut it.

Note that for style reasons I'd just use Encoding.ASCII. The static
ASCII property is inherited from Encoding in ASCIIEncoding, but I
believe it's better style to make it obvious where it's declared.

Mind you, both of these are better than creating a new instance of
ASCIIEncoding, as many samples do :(
 
Back
Top