C# 在c中将Base64值转换为字符串时,字符串值system.byte[]#
我有两个LDIF文件,从中读取值并使用c进行比较# LDIF中的C# 在c中将Base64值转换为字符串时,字符串值system.byte[]#,c#,base64,byte,system,encode,C#,Base64,Byte,System,Encode,我有两个LDIF文件,从中读取值并使用c进行比较# LDIF中的属性:value之一是base64值,需要将其转换为UTF-8格式 displayName:: Rmlyc3ROYW1lTGFzdE5hbWU= 所以我想使用string->byte[],但是我不能使用上面的displayName值作为string byte[] newbytes = Convert.FromBase64String(displayname); string displaynamereadable = Encodi
属性: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,它可以工作,但它插入了很多具有原始值的新字符
二进制格式化程序的快照:
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文本。因此,如果属性值[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
@RDN。如果有效,请将问题标记为已解决。