Decode IMAP UTF7 mailbox names in C#

How to use

foreach (string item in mailboxList) {
  string mailboxName = ImapUtf7Encoder.Decode(item);
}

Implementation

public class ImapUtf7Encoder
{
  private static string DecodeBase64Imap(string value)
  {
    using (var enc = new Encoder())
    {
      enc.EncodeMethod = EncodeMethod.Base64;

      var b = enc.DecodeBytes(value.Replace(',', '/'), "UTF-7");
      return Translator.GetString(b, "UTF-16BE");
    }
  }

  public static string Decode(string value)
  {
    string result = "";
    int n = value.Length;
    int h = 0;

    while (h < n)
    {
      int t = value.IndexOf('&', h);
      if (t < 0)
      {
        t = n;
      }

      result += value.Substring(h, t - h);
      h = t + 1;
      if (h >= n) break;

      t = value.IndexOf('-', h);
      if (t < 0)
      {
        t = n;
      }

      int k = t - h;

      if (k == 0)
      {
        result += '&';
      }
      else
      {
        result += DecodeBase64Imap(value.Substring(h, k));
      }
      h = t + 1;
    }

    return result;
  }
}

Add Feedback