Consider a string variable str, a MemoryStream instance ms, and a byte array bt. Below are common conversion patterns among these types in C#.
1. String to Byte Array
byte[] bt = System.Text.Encoding.Default.GetBytes("example");
byte[] bt = Convert.FromBase64String("base64EncodedString");
Different encodings can be used explicitly:
System.Text.Encoding.Unicode.GetBytes(str);
System.Text.Encoding.UTF8.GetBytes(str);
System.Text.Encoding.GetEncoding("gb2312").GetBytes(str);
Example with mixed content:
string input = "中国?ss123?";
byte[] bytes = System.Text.Encoding.GetEncoding("gb2312").GetBytes(input); // Length: 12
string firstChar = System.Text.Encoding.GetEncoding("gb2312")
.GetString(new byte[] { bytes[0], bytes[1] }); // "中"
ASCII example:
byte[] asciiBytes = { 97, 98, 99, 100, 101, 102 };
string result = System.Text.Encoding.ASCII.GetString(asciiBytes); // "abcdef"
Key meethods in Encoding:
GetString: Decodes a byte array into a string.GetChars: Decodes bytes into a character array.GetBytes: Encodes characters into a byte array.GetByteCount: Returns the number of bytes needed to encode a character sequence.GetCharCount: Returns the number of characters from decoding a byte sequence.GetDecoder: Returns a decoder for converting bytes to characters.GetEncoder: Returns an encoder for converting characters to bytes.
2. Byte Array to String
string str = System.Text.Encoding.Default.GetString(bt);
string str = Convert.ToBase64String(bt);
3. String to MemoryStream
MemoryStream ms = new MemoryStream(System.Text.Encoding.Default.GetBytes("text"));
MemoryStream ms = new MemoryStream(Convert.FromBase64String("base64String"));
4. MemoryStream to String
string str = Convert.ToBase64String(ms.ToArray());
string str = System.Text.Encoding.Default.GetString(ms.ToArray());
5. Byte Array to MemoryStream
MemoryStream ms = new MemoryStream(bt);
// Or initialize empty and write:
MemoryStream ms = new MemoryStream();
ms.Write(bt, 0, bt.Length);
6. MemoryStream to Byte Array
byte[] bt = ms.ToArray();
// Note: The following is incorrect as written in original; corrected version:
MemoryStream ms = new MemoryStream();
ms.Write(bt, 0, bt.Length); // Writing bt into ms
// To read back:
ms.Position = 0;
byte[] output = new byte[ms.Length];
ms.Read(output, 0, output.Length);