Saturday, August 27, 2011

C#: convert string to byte array


Share at Facebook

In java, you can easily call the getBytes() from the String class. But at c# you have to use the GetBytes() method from the System.Text. Here is the simple piece of code.

If your string contains the UTF-8 characters, that case this code will be suitable:

byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(string);


When you are wanting the byte array from plain text. That case it will be:

byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(string);




No comments: