字符串值system.byte [],同时将Base64值覆盖为c#中的字符串

问题描述 投票:0回答:1

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

displayName:: Rmlyc3ROYW1lTGFzdE5hbWU=

所以我想到了使用字符串-> byte [],但是我无法将上述displayName值用作字符串

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作为String用户使用,以便获得编码的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"

谢谢,

c# base64 byte system encode
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.