Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

c# - 在C#中将字符串转换为字节数组(Converting string to byte array in C#)

I'm converting something from VB into C#.

(我正在将某些东西从VB转换为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[]'

(参数1:无法从“对象”转换为“字节[]”)

The best overloaded method match for 'System.Text.Encoding.GetString(byte[])' has some invalid arguments

(最佳重载方法匹配'System.Text.Encoding.GetString(byte [])'有一些无效的参数)

I tried to fix the code based on this post, but still no success

(我试图根据这篇文章修复代码,但仍然没有成功)

string User = Encoding.UTF8.GetString("user", 0);

Any suggestions?

(有什么建议么?)

  ask by nouptime translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(如果您可以在继承的代码中找到用于创建字节数组的编码,则应该进行设置。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...