Convert a Byte Array to a String in C#

by Al Beecy January 10, 2009
In a previous article, Convert a String to a Byte Array in C#, I showed how to convert a string to a byte array. In this article, is an example that shows how to go from a byte array back to a string.

First, you'll need this enum:

#region EncodingType enum
/// <summary>
/// Encoding Types.
/// </summary>
public enum EncodingType
{
    ASCII,
    Unicode,
    UTF7,
    UTF8
}
#endregion

Then this function: 

#region ByteArrayToString
/// <summary>
/// Converts a byte array to a string using Unicode encoding.
/// </summary>
/// <param name="bytes">Array of bytes to be converted.</param>
/// <returns>string</returns>
public static string ByteArrayToString(byte[] bytes)
{
    return ByteArrayToString(bytes, EncodingType.Unicode);
}
/// <summary>
/// Converts a byte array to a string using specified encoding.
/// </summary>
/// <param name="bytes">Array of bytes to be converted.</param>
/// <param name="encodingType">EncodingType enum.</param>
/// <returns>string</returns>
public static string ByteArrayToString(byte[] bytes, EncodingType encodingType)
{
    System.Text.Encoding encoding=null;
    switch (encodingType)
    {
        case EncodingType.ASCII:
            encoding=new System.Text.ASCIIEncoding();
            break;   
        case EncodingType.Unicode:
            encoding=new System.Text.UnicodeEncoding();
            break;   
        case EncodingType.UTF7:
            encoding=new System.Text.UTF7Encoding();
            break;   
        case EncodingType.UTF8:
            encoding=new System.Text.UTF8Encoding();
            break;   
    }
    return encoding.GetString(bytes);
}
#endregion

Tags:

C#

Comments

January 10, 2009 #

DotNetKicks.com

Trackback from DotNetKicks.com

Convert a Byte Array to a String in C#

DotNetKicks.com

January 23, 2009 #

Web Development Community

Trackback from Web Development Community

Convert a Byte Array to a String in C#

Web Development Community

October 30, 2009 #

saif

is there a way to tell whats this byte array encoding ?

saif Iraq

November 5, 2009 #

Al Beecy

Saif, unfortunately, no. Bytes is bytes.

There are a lot of routines floating around the net that attempt to do this for strings, but all they can really do is make a reasonable guess by examining the contents of the string.

Best thing you can do is know what your inputs are to begin with.

Al Beecy United States

Powered by BlogEngine.NET1.5.0.7 | Theme by Mads Kristensen