Convert string to byte array and byte array to string

How do we convert a string to a byte array (byte[]) and the other way around. The most simple way to do this is with the Encoding class:

String to bytes:
byte[] bytes = Encoding.UTF8.GetBytes("foo");

Bytes to string:
string foo = Encoding.ASCII.GetString(bytes);

But what if you don’t know the encoding type? Well you can use the following code snippet to change the string to byte array and byte array to string:

String to bytes:
   1:  public static byte[] ConvertStringToBytes(string input)
   2:  {
   3:    MemoryStream stream = new MemoryStream();
   4:    
   5:    using (StreamWriter writer = new StreamWriter(stream))
   6:    {
   7:      writer.Write(input);
   8:      writer.Flush();
   9:    }
  10:   
  11:    return stream.ToArray();
  12:  }

Bytes to string:
   1:  public static string ConvertBytesToString(byte[] bytes)
   2:  {
   3:    string output = String.Empty;
   4:   
   5:    MemoryStream stream = new MemoryStream(bytes);
   6:    stream.Position = 0;
   7:   
   8:    using (StreamReader reader = new StreamReader(stream))
   9:    {
  10:      output = reader.ReadToEnd();
  11:    }
  12:   
  13:    return output;
  14:  }
 
With this snippets you can convert if you don’t know the encoding of a certain string.

7 Comments

  • thanks a lot ...........



  • Hi Erwin,

    I always knew you were wicked smart. Thanks for sharing this!

    Cheers,

    Richard

  • thanks your share!

  • on my screen some of the code on the right side of this page is cut off - can you fix this?

  • Thanks Simple and useful

  • Thanks Simple and useful

  • Although very useful, I believe you missed one key step here...

    You are leaving a left over memorystream that hasnt been disposed. Although the GC will clean that up it is best to close and dispose all your Stream objects.

    I personally prefer this markup..

    public static string ConvertBytesToString(byte[] bytes)
    {
    string output = String.Empty;
    using (MemoryStream stream = new MemoryStream(bytes))
    {
    stream.Position = 0;
    using (StreamReader reader = new StreamReader(stream))
    {
    output = reader.ReadToEnd();
    }
    }
    return output;
    }

    public static byte[] ToByteArray(this string input)
    {
    byte[] outByte = new byte[] { };
    using (MemoryStream stream = new MemoryStream())
    {
    using (StreamWriter writer = new StreamWriter(stream))
    {
    writer.Write(input);
    writer.Flush();
    }
    outByte = stream.ToArray();
    }
    return outByte;
    }

Comments have been disabled for this content.