2.14. Passing a String to a Method that Accepts Only a Byte[ ]

Problem

Many methods in the FCL accept a byte[] consisting of characters instead of a string. Some of these methods include:

System.Net.Sockets.Socket.Send
System.Net.Sockets.Socket.SendTo
System.Net.Sockets.Socket.BeginSend
System.Net.Sockets.Socket.BeginSendTo
System.Net.Sockets.NetworkStream.Write
System.Net.Sockets.NetworkStream.BeginWrite
System.IO.BinaryWriter.Write
System.IO.FileStream.Write
System.IO.FileStream.BeginWrite
System.IO.MemoryStream.Write
System.IO.MemoryStream.BeginWrite
System.Security.Cryptography.CryptoStream.Write
System.Security.Cryptography.CryptoStream.BeginWrite
System.Diagnostics.EventLog.WriteEntry

In many cases, you might have a string that you need to pass into one of these methods or some other method that only accepts a byte[]. You need a way to break up this string into a byte[].

Solution

To convert a string to a byte array of ASCII values, use the GetBytes method on an instance of the ASCIIEncoding class:

using System;
using System.Text;

public static byte[] ToASCIIByteArray(string characters)
{
    ASCIIEncoding encoding = new ASCIIEncoding( );
    int numberOfChars = encoding.GetByteCount(characters);
    byte[] retArray = new byte[numberOfChars];

    retArray = encoding.GetBytes(characters);

    return (retArray);
}

To convert a string to a byte array of Unicode values, use the UnicodeEncoding class:

public static byte[] ToUnicodeByteArray(string characters) { UnicodeEncoding encoding = new UnicodeEncoding( ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.