在 c# 中将 Base64 值转换为字符串时的字符串值 system.byte[]

String value system.byte[] while coverting Base64 value to string in c#

我有两个 LDIF 文件,我从中读取值并将其用于使用 c# 进行比较 LDIF中有一个attribute: value是base64值,需要转成UTF-8格式

displayName:: Rmlyc3ROYW1lTGFzdE5hbWU=

所以我想到了使用 string -> byte[],但是我无法将上面的 displayName 值用作 string

byte[] newbytes = Convert.FromBase64String(displayname);
string displaynamereadable = Encoding.UTF8.GetString(newbytes);

在我的 C# 代码中,我这样做是为了从 ldif 文件中检索值

for(Entry entry ldif.ReadEntry() ) //reads value from ldif for particular user's
{
    foreach(Attr attr in entry)   //here attr gives attributes of a particular user
    {
        if(attr.Name.Equals("displayName"))
        {
            string attVal = attr.Value[0].ToString();       //here the value of String attVal is system.Byte[], so not able to use it in the next line
            byte[] newbytes = Convert.FromBase64String(attVal);   //here it throws an error mentioned below 
            string displaynamereadable = Encoding.UTF8.GetString(attVal);
        }
    }
}

错误:

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

我正在尝试将 attVal 用作字符串,以便我可以获得编码的 UTf-8 值,但它会引发错误。 我也尝试使用 BinaryFormatter 和 MemoryStream,它有效但它插入了很多具有原始值的新字符。

BinaryFormatter 的快照:

object obj = attr.Value[0];
byte[] bytes = null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
   {
      bf.Serialize(ms, obj);
      bytes = (ms.ToArray());
   }
 string d = Encoding.UTF8.GetString(bytes);

所以编码后的结果应该是:"FirstNameLastName"

但它给出 "\u0002 \u004 \u004 ...................FirstNameLastName\v"

谢谢,

Base64 旨在通过仅支持纯文本的传输通道发送二进制数据,因此,Base64 始终是 ASCII 文本。因此,如果 attr.Value[0] 是字节数组,只需使用 ASCII 编码将这些字节解释为字符串:

String attVal = Encoding.ASCII.GetString(attr.Value[0] as Byte[]);
Byte[] newbytes = Convert.FromBase64String(attVal);
String displaynamereadable = Encoding.UTF8.GetString(newbytes);

另请注意,您上面的代码将 attVal 输入到最后一行,而不是 newbytes