Recipe 2.13 Converting a String Returned as a Byte[ ] Back into a String
Problem
Many methods in the FCL return a
byte[] consisting of characters instead of a
string. Some of these methods include:
System.Net.Sockets.Socket.Receive
System.Net.Sockets.Socket.ReceiveFrom
System.Net.Sockets.Socket.BeginReceive
System.Net.Sockets.Socket.BeginReceiveFrom
System.Net.Sockets.NetworkStream.Read
System.Net.Sockets.NetworkStream.BeginRead
System.IO.BinaryReader.Read
System.IO.BinaryReader.ReadBytes
System.IO.FileStream.Read
System.IO.FileStream.BeginRead
System.IO.MemoryStream // Constructor
System.IO.MemoryStream.Read
System.IO.MemoryStream.BeginRead
System.Security.Cryptography.CryptoStream.Read
System.Security.Cryptography.CryptoStream.BeginRead
System.Diagnostics.EventLogEntry.Data
In many cases, this byte[] might contain
ASCII or Unicode encoded characters. You need a
way to recombine this byte[] to obtain the
original string.
Solution
To convert a byte
array of ASCII values to a complete
string, use the following
method:
using System;
using System.Text;
public static string FromASCIIByteArray(byte[] characters)
{
ASCIIEncoding encoding = new ASCIIEncoding( );
string constructedString = encoding.GetString(characters);
return (constructedString);
}
To convert a byte array of
Unicode values (UTF-16 encoded) to a complete
string, use the following
method:
public static string FromUnicodeByteArray(byte[] characters)
{
UnicodeEncoding encoding = new UnicodeEncoding( );
string constructedString = encoding.GetString(characters);
return (constructedString);
}
Discussion
The
GetString method of the
ASCIIEncoding class converts 7-bit ASCII
characters contained in a byte array to a
string. Any value larger than 127 is converted to
the ? character. The
ASCIIEncoding class can be found in the
System.Text namespace. The
GetString method is overloaded to accept
additional arguments as well. The overloaded versions of the method
convert all or part of a string to ASCII and then
store the result in a specified range inside a
byte array.
The GetString method returns a
string containing the converted
byte array of ASCII characters.
The
GetString method of the
UnicodeEncoding class converts Unicode characters
into 16-bit Unicode values. The UnicodeEncoding
class can be found in the System.Text namespace.
The GetString method returns a
string containing the converted
byte array of Unicode characters.
See Also
See the "ASCIIEncoding Class" and
"UnicodeEncoding Class" topics in
the MSDN documentation.
|