
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Passing a String to a Method That Accepts only a Byte[ ]
|
59
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 meth-
ods 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