QuotedPrintableEncoding.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.IO;
  3. using System.Text.RegularExpressions;
  4. namespace Ant.Service.Utilities
  5. {
  6. /// <summary>
  7. /// This class is based on the QuotedPrintable class written by Bill Gearhart
  8. /// found at http://www.aspemporium.com/classes.aspx?cid=6
  9. /// </summary>
  10. public static class QuotedPrintableEncoding
  11. {
  12. private const string Equal = "=";
  13. private const string HexPattern = "(\\=([0-9A-F][0-9A-F]))";
  14. public static string Decode(string contents)
  15. {
  16. if (contents == null)
  17. {
  18. throw new ArgumentNullException("contents");
  19. }
  20. using (StringWriter writer = new StringWriter())
  21. {
  22. using (StringReader reader = new StringReader(contents))
  23. {
  24. string line;
  25. while ((line = reader.ReadLine()) != null)
  26. {
  27. /*remove trailing line whitespace that may have
  28. been added by a mail transfer agent per rule
  29. #3 of the Quoted Printable section of RFC 1521.*/
  30. line.TrimEnd();
  31. if (line.EndsWith(Equal))
  32. {
  33. writer.Write(DecodeLine(line));
  34. } //handle soft line breaks for lines that end with an "="
  35. else
  36. {
  37. writer.WriteLine(DecodeLine(line));
  38. }
  39. }
  40. }
  41. writer.Flush();
  42. return writer.ToString();
  43. }
  44. }
  45. private static string DecodeLine(string line)
  46. {
  47. if (line == null)
  48. {
  49. throw new ArgumentNullException("line");
  50. }
  51. Regex hexRegex = new Regex(HexPattern, RegexOptions.IgnoreCase);
  52. return hexRegex.Replace(line, new MatchEvaluator(HexMatchEvaluator));
  53. }
  54. private static string HexMatchEvaluator(Match m)
  55. {
  56. int dec = Convert.ToInt32(m.Groups[2].Value, 16);
  57. char character = Convert.ToChar(dec);
  58. return character.ToString();
  59. }
  60. }
  61. }