Кодировка Quoted-Printable UTF-8 - C#

Узнай цену своей работы

Формулировка задачи:

Здравствуйте ! Пытаюсь раскодировать Quoted-Printable строку... код работает нормально для любой кодировки, кроме UTF-8, я не знаю, почему он не может декодировать UTF-8. Как декодировать Quoted-Printable строку UTF-8 (кириллица) в нормальный читаемый вид?
Листинг программы
  1. public static string DecodeEncodedWordValue(string mimeString)
  2. {
  3. var regex = new Regex(@"=\?(?<charset>.*?)\?(?<encoding>[qQbB])\?(?<value>.*?)\?=");
  4. var encodedString = mimeString;
  5. var decodedString = string.Empty;
  6. while (encodedString.Length > 0)
  7. {
  8. var match = regex.Match(encodedString);
  9. if (match.Success)
  10. {
  11. // If the match isn't at the start of the string, copy the initial few chars to the output
  12. decodedString += encodedString.Substring(0, match.Index);
  13. var charset = match.Groups["charset"].Value;
  14. var encoding = match.Groups["encoding"].Value.ToUpper();
  15. var value = match.Groups["value"].Value;
  16. if (encoding.Equals("B"))
  17. {
  18. // Encoded value is Base-64
  19. var bytes = Convert.FromBase64String(value);
  20. decodedString += Encoding.GetEncoding(charset).GetString(bytes);
  21. }
  22. else if (encoding.Equals("Q"))
  23. {
  24. // Encoded value is Quoted-Printable
  25. // Parse looking for =XX where XX is hexadecimal
  26. var regx = new Regex("(\\=([0-9A-F][0-9A-F]))", RegexOptions.IgnoreCase);
  27. decodedString += regx.Replace(value, new MatchEvaluator(delegate(Match m)
  28. {
  29. byte[] bytes = new byte[m.Value.Length / 3];
  30. for (int i = 0; i < bytes.Length; i++)
  31. {
  32. string hex = m.Value.Substring(i * 3 + 1, 2);
  33. int iHex = Convert.ToInt32(hex, 16);
  34. bytes[i] = Convert.ToByte(iHex);
  35. }
  36. return Encoding.GetEncoding(charset).GetString(bytes);
  37. }));
  38. decodedString = decodedString.Replace('_', ' ');
  39. }
  40. else
  41. {
  42. // Encoded value not known, return original string
  43. // (Match should not be successful in this case, so this code may never get hit)
  44. decodedString += encodedString;
  45. break;
  46. }
  47. // Trim off up to and including the match, then we'll loop and try matching again.
  48. encodedString = encodedString.Substring(match.Index + match.Length + 1);
  49. }
  50. else
  51. {
  52. // No match, not encoded, return original string
  53. decodedString += encodedString;
  54. break;
  55. }
  56. }
  57. return decodedString;
  58. }

Решение задачи: «Кодировка Quoted-Printable UTF-8»

textual
Листинг программы
  1. public static string DecodeEncodedWordValue(string mimeString) // перевод темы и отправителя письма из кодировки  quoted printable
  2.         {
  3.             var regex = new Regex(@"=\?(?<charset>.*?)\?(?<encoding>[qQbB])\?(?<value>.*?)\?=");
  4.             var encodedString = mimeString;
  5.             var decodedString = string.Empty;
  6.             while (encodedString.Length > 0)
  7.             {
  8.                 var match = regex.Match(encodedString);
  9.                 if (match.Success)
  10.                 {
  11.                     decodedString += encodedString.Substring(0, match.Index);
  12.                     var charset = match.Groups["charset"].Value;
  13.                     var encoding = match.Groups["encoding"].Value.ToUpper();
  14.                     var value = match.Groups["value"].Value;
  15.                     if (encoding.Equals("B"))
  16.                     {
  17.                         // Encoded value is Base-64
  18.                         var bytes = Convert.FromBase64String(value);
  19.                         decodedString += Encoding.GetEncoding(charset).GetString(bytes);
  20.                     }
  21.                     else if (encoding.Equals("Q"))
  22.                     {
  23.                         // Encoded value is Quoted-Printable
  24.                         // Parse looking for =XX where XX is hexadecimal
  25.                         var regx = new Regex("(\\=([0-9A-F][0-9A-F]))", RegexOptions.IgnoreCase);
  26.                         decodedString += regx.Replace(value, new MatchEvaluator(delegate(Match m)
  27.                             {
  28.                                 byte[] bytes = new byte[m.Value.Length / 3];
  29.                                 for (int i = 0; i < bytes.Length; i++)
  30.                                 {
  31.                                     string hex = m.Value.Substring(i * 3 + 1, 2);
  32.                                     int iHex = Convert.ToInt32(hex, 16);
  33.                                     bytes[i] = Convert.ToByte(iHex);
  34.                                 }
  35.                                 return Encoding.GetEncoding(charset).GetString(bytes);
  36.                             }));
  37.                         decodedString = decodedString.Replace('_', ' ');
  38.                     }
  39.                     else
  40.                     {
  41.                         // Encoded value not known, return original string
  42.                         // (Match should not be successful in this case, so this code may never get hit)
  43.                         decodedString += encodedString;
  44.                         break;
  45.                     }
  46.                     // Trim off up to and including the match, then we'll loop and try matching again.
  47.                     encodedString = encodedString.Substring(match.Index + match.Length);
  48.                 }
  49.                 else
  50.                 {
  51.                     // No match, not encoded, return original string
  52.                     decodedString += encodedString;
  53.                     break;
  54.                 }
  55.             }
  56.             return decodedString;
  57.         }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

9   голосов , оценка 4.222 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут