如何在C#中将“=?utf-8?B?…?=”解码为字符串

我使用Visual Studio 2010,C#使用IMAP读取Gmail收件箱,它可以作为魅力,但我认为Unicode不完全支持,因为我无法轻松获得波斯语(波斯语)字符串。

例如,我有我的字符串: سلام ,但IMAP给了我: "=?utf-8?B?2LPZhNin2YU=?="

如何将其转换为原始字符串? 将utf-8转换为字符串的任何提示?

我们来看看MIME编码的含义:

 =?utf-8?B?...something...?= ^ ^ | +--- The bytes are Base64 encoded | +---- The string is UTF-8 encoded 

所以,为了解码这个,从你的字符串中取出...something... (在你的情况下为2LPZhNin2YU= )然后

  1. 反转Base64编码

     var bytes = Convert.FromBase64String("2LPZhNin2YU="); 
  2. 将字节解释为UTF8字符串

     var text = Encoding.UTF8.GetString(bytes); 

text现在应该包含所需的结果。


可以在维基百科中找到此格式的说明:

你拥有的是一个MIME编码的字符串。 .NET不包含用于MIME解码的库,但您可以自己实现它或使用库 。

他在这里

  public static string Decode(string s) { return String.Join("", Regex.Matches(s ?? "", @"(?:=\?)([^\?]+)(?:\?B\?)([^\?]*)(?:\?=)").Cast().Select(m => { string charset = m.Groups[1].Value; string data = m.Groups[2].Value; byte[] b = Convert.FromBase64String(data); return Encoding.GetEncoding(charset).GetString(b); })); }