Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Friday, November 23, 2012

Convert string to byte array and byte array to string (C#)

To convert from string into byte array, we can use Encoding class to convert into specific format such as ASCII or UTF8.

Example: 
using System.Text;
...
string str = "Hello, World!!!";
byte[] byteData = Encoding.UTF8.GetBytes(str);
On the opposite way, to convert back from byte array into string, we can simply use StreamReader to read it from MemoryStream.

Example:
string output = string.Empty;
byte[] byteData = ...;
using (var memoryStream = new MemoryStream(byteData))
{
     using (var streamReader = new StreamReader(memoryStream))
     {
          output = streamReader.readToEnd();
     }
}

No comments:

Post a Comment