//used when the length of the header name itself is known (i.e. Subject : ) internal static string EncodeHeaderValue(string value, Encoding encoding, bool base64Encoding, int headerLength) { //no need to encode if it's pure ascii if (IsAscii(value, false)) { return(value); } if (encoding == null) { encoding = Encoding.GetEncoding(DefaultCharSet); } EncodedStreamFactory factory = new EncodedStreamFactory(); IEncodableStream stream = factory.GetEncoderForHeader(encoding, base64Encoding, headerLength); byte[] buffer = encoding.GetBytes(value); stream.EncodeHeaderBytes(buffer, encoding); return(stream.GetEncodedString()); }
internal static string DecodeHeaderValue(string value) { if (string.IsNullOrEmpty(value)) { return(string.Empty); } string newValue = string.Empty; //split strings, they may be folded. If they are, decode one at a time and append the results string[] substringsToDecode = value.Split(s_headerValueSplitChars, StringSplitOptions.RemoveEmptyEntries); foreach (string foldedSubString in substringsToDecode) { //an encoded string has as specific format in that it must start and end with an //'=' char and contains five parts, separated by '?' chars. //the first and last part are therefore '=', the second part is the byte encoding (B or Q) //the third is the unicode encoding type, and the fourth is encoded message itself. '?' is not valid inside of //an encoded string other than as a separator for these five parts. //If this check fails, the string is either not encoded or cannot be decoded by this method string[] subStrings = foldedSubString.Split(s_questionMarkSplitChars); if ((subStrings.Length != 5 || subStrings[0] != "=" || subStrings[4] != "=")) { return(value); } string charSet = subStrings[1]; bool base64Encoding = (subStrings[2] == "B"); byte[] buffer = Encoding.ASCII.GetBytes(subStrings[3]); int newLength; EncodedStreamFactory encoderFactory = new EncodedStreamFactory(); IEncodableStream s = encoderFactory.GetEncoderForHeader(Encoding.GetEncoding(charSet), base64Encoding, 0); newLength = s.DecodeBytes(buffer, 0, buffer.Length); Encoding encoding = Encoding.GetEncoding(charSet); newValue += encoding.GetString(buffer, 0, newLength); } return(newValue); }