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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10828807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:25:59  来源:igfitidea点击:

How to Decode "=?utf-8?B?...?=" to string in C#

c#stringunicodeutf-8

提问by Ali_dotNet

I use Visual Studio 2010, C# to read Gmail inbox using IMAP, it works as a charm, but I think Unicode is not fully supported as I cannot get Persian (Farsi) strings easily.

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

For instance I have my string: ????, but IMAPgives me: "=?utf-8?B?2LPZhNin2YU=?=".

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

How can I convert it to original string? any tips from converting utf-8 to string?

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

采纳答案by Heinzi

Let's have a look at the meaning of the MIME encoding:

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

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

So, to decode this, take the ...something...out of your string (2LPZhNin2YU=in your case) and then

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

  1. reverse the Base64 encoding

    var bytes = Convert.FromBase64String("2LPZhNin2YU=");
    
  2. interpret the bytes as a UTF8 string

    var text = Encoding.UTF8.GetString(bytes);
    
  1. 反转 Base64 编码

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

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

textshould now contain the desired result.

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



A description of this format can be found in Wikipedia:

这种格式的描述可以在维基百科中找到:

回答by Jirka Hanika

What you have is a MIME encoded string. .NET does not include libraries for MIME decoding, but you can either implement this yourselfor use a library.

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

回答by dima_horror

here he is

他在这里

    public static string Decode(string s)
    {
        return String.Join("", Regex.Matches(s ?? "", @"(?:=\?)([^\?]+)(?:\?B\?)([^\?]*)(?:\?=)").Cast<Match>().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);
        }));
    }