Convert byte array back to string in C#
In C#, when converting a string to a byte array, the Encoding
class provides multiple methods to encode and decode different character sets. If you encounter an error when converting an object to a byte array, such as "Cannot convert from 'object' to 'byte[]'", it means that the input provided was not a byte array.
To fix this problem, you need to get the original byte array from the VB code, or determine how the byte array was created. Once you know which encoding was used, you can convert the byte array back to a string using the corresponding encoding method.
For example, if the byte array was created using ASCII encoding, you can use Encoding.ASCII.GetBytes()
to encode the string to the byte array, and use Encoding.ASCII.GetString()
to decode the byte array back to a string.
Example:
<code class="language-csharp">using System.Text; // 使用 ASCII 编码将字符串转换为字节数组 byte[] bytes = Encoding.ASCII.GetBytes("Hello World!"); // 使用 ASCII 编码将字节数组转换回字符串 string message = Encoding.ASCII.GetString(bytes);</code>
Additional notes:
Encoding
class contains various encoding methods such as UTF8, Unicode and UTF32 to support different character sets. The above is the detailed content of How Can I Convert a Byte Array Back to a String in C#?. For more information, please follow other related articles on the PHP Chinese website!