我正在把VB转换成c#。这条语句的语法有问题:

if ((searchResult.Properties["user"].Count > 0))
{
    profile.User = System.Text.Encoding.UTF8.GetString(searchResult.Properties["user"][0]);
}

然后我看到以下错误:

参数1:不能将'object'转换为'byte[]' 匹配的最佳重载方法 'System.Text.Encoding.GetString(byte[])'有一些无效的参数

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

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

有什么建议吗?


当前回答

基于阿里的回答,我会推荐一个扩展方法,允许你有选择地传入你想使用的编码:

using System.Text;
public static class StringExtensions
{
    /// <summary>
    /// Creates a byte array from the string, using the 
    /// System.Text.Encoding.Default encoding unless another is specified.
    /// </summary>
    public static byte[] ToByteArray(this string str, Encoding encoding = Encoding.Default)
    {
        return encoding.GetBytes(str);
    }
}

然后像下面这样使用它:

string foo = "bla bla";

// default encoding
byte[] default = foo.ToByteArray();

// custom encoding
byte[] unicode = foo.ToByteArray(Encoding.Unicode);

其他回答

这个工作为我,之后我可以转换把我的照片在bytea字段在我的数据库。

using (MemoryStream s = new MemoryStream(DirEntry.Properties["thumbnailphoto"].Value as byte[]))
{
    return s.ToArray();
}

使用这个

byte[] myByte= System.Text.ASCIIEncoding.Default.GetBytes(myString);

在c# 11中,你可以使用UTF-8字符串字面量,这使得它超级简单,具有更好的性能,并且没有内存分配。

byte[] array = "some text";

或者,如果你已经有一个字符串值:

string input = "some text"; 
byte[] array = input;

这是一个使用旧的UTF-8编码方式(GetBytes)和c# 11 UTF-8字符串文字方式(GetBytesNew)之间的区别的例子。

c# 11之前

ReadOnlySpan<byte> before = System.Text.Encoding.UTF8.GetBytes("hello!");

在c# 11中,你现在可以简单地给你的字符串字面量添加一个u8后缀,让它们立即变成UTF-8格式

ReadOnlySpan<byte> now = "hello!"u8;

阅读UTF-8字符串字面量的文档

static byte[] GetBytes(string str)
{
     byte[] bytes = new byte[str.Length * sizeof(char)];
     System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
     return bytes;
}

static string GetString(byte[] bytes)
{
     char[] chars = new char[bytes.Length / sizeof(char)];
     System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
     return new string(chars);
}