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.