O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required