2.11. 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.Diagnostics.EventLog.WriteEntry System.IO.BinaryWriter.Write System.IO.FileStream.Write System.IO.FileStream.BeginWrite System.IO.MemoryStream.Write System.IO.MemoryStream.BeginWrite 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.Security.Cryptography.CryptoStream.Write System.Security.Cryptography.CryptoStream.BeginWrite
In many cases, you might have a string that you need to pass into one of these methods or some other method that accepts only a byte[]. You need a way to break up this string into a byte[].
Solution
To convert a string to a byte[] of ASCII values, use the GetBytes method on the Encoding class:
byte[] retArray = Encoding.ASCII.GetBytes(characters);
To convert a string to a byte[] of Unicode values, use the GetBytes method on the Encoding class:
byte[] retArray = Encoding.Unicode.GetBytes(characters);
Discussion
The GetBytes method of the Encoding class (returned by the ASCII property) converts ASCII characters—contained in either a char[] or a string—into a byte[] of 7-bit ASCII values. Any value larger than 127 (0x7F) is converted to the ? character. The Encoding class can be found in the System.Text ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access