FCL has many methods whose return values are byte arrays containing characters instead of returning a string. Such methods are included in the following classes:
· 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
Byte arrays returned by these methods usually contain ascii or Unicode characters. In many cases, we may need to convert such byte arrays into a string.
Solution
To convert a byte array containing ASCII characters into a complete string, you can 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 containing Unicode characters to a complete string, you can 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 can convert the 7-bitsascii character in the byte array to a string. Any value greater than 127 will be converted to two characters. In the system. Text namespace, you can find the asciiencoding class, and find the getstring function of this class. You can also find that this function has multiple overload methods to support some additional parameters. The overloaded version of this method can also convert some characters in a byte array into strings.
The getstring method that converts a byte array to a string can be found in the unicodeencoding class of the system. Text namespace. This method converts a byte array containing 16-bitsunicode characters to a string. Like the getstring method of the asciiencoding class, this method also contains an overloaded version that converts a specific part of the byte array to a string.