【发布时间】:2020-04-23 11:32:50
【问题描述】:
我有两个 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 用作字符串,以便我可以获得编码的 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