Byte array to string in C#

In C#, you can convert a byte array to a string using different encodings. When you convert a byte array to a string, you are essentially decoding the bytes back into their original character representation. Let's explore two common methods to achieve this:

Using Encoding.GetString() Method

You can use the Encoding.GetString() method to convert a byte array to a string. This method takes the byte array as input and returns the corresponding string representation.

using System; using System.Text; byte[] byteArray = new byte[] { 72, 101, 108, 108, 111 }; // Example byte array // Convert byte array to string using UTF-8 encoding string result = Encoding.UTF8.GetString(byteArray); // Result: "Hello"

In this example, the byte array contains the ASCII values of the characters "Hello." The GetString() method with the Encoding.UTF8 argument decodes the bytes using the UTF-8 encoding and returns the string representation.

Using Convert.ToBase64String()

If you have a byte array that represents binary data (e.g., images, files), you can use Convert.ToBase64String() to convert the byte array to a Base64 string.

byte[] byteArray = new byte[] { 72, 101, 108, 108, 111 }; // Example byte array // Convert byte array to Base64 string string base64String = Convert.ToBase64String(byteArray); // Result: "SGVsbG8="

In this example, the byte array is converted to its Base64 string representation. Base64 encoding is commonly used to represent binary data in a textual format.

Byte array to string C# vb.Net

Keep in mind that when converting a byte array to a string, the correct encoding must be used to interpret the bytes correctly. In the first method, Encoding.GetString() uses the specified encoding to convert the bytes to characters. In the second method, Convert.ToBase64String() converts the bytes to a textual representation using Base64 encoding.

Conclusion

When decoding a byte array back to a string, make sure to use the same encoding that was used during the conversion from the string to the byte array. This ensures that the characters are correctly interpreted, and you get the original string back.