Home >Backend Development >C++ >How Do I Correctly Convert Strings to Byte Arrays and Vice Versa in C#?

How Do I Correctly Convert Strings to Byte Arrays and Vice Versa in C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-23 06:17:08164browse

How Do I Correctly Convert Strings to Byte Arrays and Vice Versa in C#?

Conversion of string and byte array in C#

String to byte array conversion may cause problems when migrating code from VB to C#. This is especially true when dealing with properties of returned objects rather than byte arrays.

Consider the following problematic code:

<code class="language-csharp">if ((searchResult.Properties["user"].Count > 0))
{
    profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]);
}</code>

The error encountered in this code stems from the expectation that the property value will be a byte array, when in fact it is an object. In order to solve this problem, it is important to understand the encoding used to convert the string to the byte array in the first place.

If the byte array was created using ASCII encoding, it should be converted back to a string using:

<code class="language-csharp">string someString = Encoding.ASCII.GetString(bytes);</code>

Similarly, if UTF8 encoding is used, the appropriate way to convert a byte array to a string is:

<code class="language-csharp">string someString = Encoding.UTF8.GetString(bytes);</code>

By identifying the encoding used to create the byte array, you can ensure that the string conversion is performed correctly.

The above is the detailed content of How Do I Correctly Convert Strings to Byte Arrays and Vice Versa in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn