Users Online

We have 35 guests online
String to Byte Array Conversion in C# and VB.NET (and back) PDF Print E-mail
Written by Zack MIlls   
Friday, 10 September 2010 08:58

 

http://www.chilkatsoft.com/faq/DotNetStrToBytes.html

String to Byte Array Conversion in C# and VB.NET (and back)

Question:

How do I convert a string to a byte array and vica-versa in VB.NET and C#?

Answer:

' VB.NET to convert a string to a byte array
Public Shared Function StrToByteArray(str As String) As Byte()
   Dim encoding As New System.Text.UTF8Encoding()
   Return encoding.GetBytes(str)
End Function 'StrToByteArray

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
    System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
    return encoding.GetBytes(str);
}

' VB.NET to convert a byte array to a string:
Dim dBytes As Byte() = ...
Dim str As String
Dim enc As New System.Text.UTF8Encoding()
str = enc.GetString(dBytes)

// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
str = enc.GetString(dBytes);