Converting string to byte array in C#
I'm quite new to C#. I'm converting something from VB into C#. Having a problem with the syntax of this statement:
if ((searchResult.Properties["user"].Count > 0))
{
profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]);
}
I then see the following errors:
Argument 1: cannot convert from 'object' to 'byte[]'
The best overloaded method match for 'System.Text.Encoding.GetString(byte[])' has some invalid arguments
I tried to fix the code based on this post, but still no success
string User = Encoding.UTF8.GetString("user", 0);
Any suggestions?
If you already have a byte array then you will need to know what type of encoding was used to make it into that byte array.
For example, if the byte array was created like this:
byte[] bytes = Encoding.ASCII.GetBytes(someString);
You will need to turn it back into a string like this:
string someString = Encoding.ASCII.GetString(bytes);
If you can find in the code you inherited, the encoding used to create the byte array then you should be set.
First of all, add the System.Text
namespace
using System.Text;
Then use this code
string input = "some text";
byte[] array = Encoding.ASCII.GetBytes(input);
Hope to fix it!
Also you can use an Extension Method to add a method to the string
type as below:
static class Helper
{
public static byte[] ToByteArray(this string str)
{
return System.Text.Encoding.ASCII.GetBytes(str);
}
}
And use it like below:
string foo = "bla bla";
byte[] result = foo.ToByteArray();
链接地址: http://www.djcxy.com/p/15890.html
上一篇: 代码中的表达式术语错误无效
下一篇: 在C#中将字符串转换为字节数组