Erwin's Blog

Developing with .NET

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.
Posted: May 01 2009, 12:19 PM by erwin21 | with 2 comment(s)
Filed under: , ,

Comments

prash said:

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

# June 22, 2009 12:12 AM

javad said:

thanks 2 u

# August 2, 2009 2:15 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)