LumiSoft.Net.Core.QuotedPrintableEncode C# (CSharp) Method

QuotedPrintableEncode() public static method

Encodes data with quoted-printable encoding.
public static QuotedPrintableEncode ( byte data ) : byte[]
data byte Data to encode.
return byte[]
        public static byte[] QuotedPrintableEncode(byte[] data)
        {
            /* Rfc 2045 6.7. Quoted-Printable Content-Transfer-Encoding

            (2) (Literal representation) Octets with decimal values of 33 through 60 inclusive,
                and 62 through 126, inclusive, MAY be represented as the US-ASCII characters which
                correspond to those octets (EXCLAMATION POINT through LESS THAN, and GREATER THAN
                through TILDE, respectively).

            (3) (White Space) Octets with values of 9 and 32 MAY be represented as US-ASCII TAB (HT) and
                SPACE characters, respectively, but MUST NOT be so represented at the end of an encoded line.
                You must encode it =XX.

            (5) Encoded lines must not be longer than 76 characters, not counting the trailing CRLF.
                If longer lines are to be encoded with the Quoted-Printable encoding, "soft" line breaks
                must be used.  An equal sign as the last character on a encoded line indicates such
                a non-significant ("soft") line break in the encoded text.

            *)  If binary data is encoded in quoted-printable, care must be taken to encode
                CR and LF characters as "=0D" and "=0A", respectively.

            */

            int lineLength = 0;
            // Encode bytes <= 33 , >= 126 and 61 (=)
            MemoryStream retVal = new MemoryStream();
            foreach(byte b in data){
                // Suggested line length is exceeded, add soft line break
                if(lineLength > 75){
                    retVal.Write(new byte[]{(byte)'=',(byte)'\r',(byte)'\n'},0,3);
                    lineLength = 0;
                }

                // We need to encode that byte
                if(b <= 33 || b >= 126 || b == 61){
                    retVal.Write(new byte[]{(byte)'='},0,1);
                    retVal.Write(Core.ToHex(b),0,2);
                    lineLength += 3;
                }
                // We don't need to encode that byte, just write it to stream
                else{
                    retVal.WriteByte(b);
                    lineLength++;
                }
            }

            return retVal.ToArray();
        }