Friday, July 4, 2008

Convert String to Byte Array

The following is a post I found from here

Figured this might come in handy for someone (or at least for me later on when I go looking for it). Below is a simple method for converting a given string to an array of bytes. Wouldn't be nice if you could just do something like this: Return myString.ToByteArray()? The String class already has ToCharArray, why not ToByteArray?

VB.NET
Imports System.Text

Public Shared Function ConvertStringToByteArray(ByVal stringToConvert As String) As Byte()

Return (New UnicodeEncoding).GetBytes(stringToConvert)

End Function

C#

using System.Text;

public static byte[] ConvertStringToByteArray(string stringToConvert)

{

return (new UnicodeEncoding()).GetBytes(stringToConvert);

}