C# .NET: Convert a String to a Byte Array

10/11/2014 10:53:11 PM

The following function takes a string and returns a byte array.

public static byte[] GetBytes(string word)
{
    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
    return encoding.GetBytes(word);
}

//alternate
public static byte[] GetBytes(string word)
{
	byte[] bytes = new byte[word.Length * sizeof(char)];
	System.Buffer.BlockCopy(word.ToCharArray(), 0, bytes, 0, bytes.Length);
	return bytes;
}