Convert string to byte array in C#
You may encounter syntax issues when trying to convert a string to a byte array in C#. Let's explore a specific case and its solution.
Question:
Trying to convert a VB object's property value to a C# byte array results in the error:
<code>Argument 1: cannot convert from 'object' to 'byte[]'</code>
Solution:
To successfully convert an attribute value, you need to know the encoding used in the original conversion. For example:
<code class="language-csharp">byte[] bytes = System.Text.Encoding.ASCII.GetBytes(originalString); string encodedString = System.Text.Encoding.ASCII.GetString(bytes);</code>
If you don't know the encoding used, you can examine the inherited code for clues. System.Text.Encoding
class provides various encodings including ASCII, UTF8, Unicode and UTF32. See the documentation for a complete list.
Please note that the code you provided:
<code class="language-csharp">string User = Encoding.UTF8.GetString("user", 0);</code>
is wrong because it tries to convert a string to a byte array without any actual data to convert. In the provided VB statement, searchResult.Properties["user"][0]
is an object containing a byte array, which needs to be accessed and converted appropriately.
The above is the detailed content of How Do I Correctly Convert a VB.NET Object's String Property to a C# Byte Array?. For more information, please follow other related articles on the PHP Chinese website!