C#将字符串转换为字节数组 [英] Converting string to byte array in C#

查看:39
本文介绍了C#将字符串转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些东西从 VB 转换成 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]);
}

然后我看到以下错误:

参数 1:无法从对象"转换为字节[]"

Argument 1: cannot convert from 'object' to 'byte[]'

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

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

我尝试根据 this 修复代码 发布,但仍然没有成功

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

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

有什么建议吗?

推荐答案

如果您已经有一个字节数组,那么您将需要知道使用什么类型的编码将其放入该字节数组中.

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.

这篇关于C#将字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆