2 // System.Web.Mail.Base64AttachmentEncoder.cs
5 // Per Arneng <pt99par@student.bth.se>
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System
.Security
.Cryptography
;
34 namespace System
.Web
.Mail
{
36 // a class that handles Base64 encoding for attachments
37 internal class Base64AttachmentEncoder
: IAttachmentEncoder
{
39 // reads bytes from a stream and writes the encoded
40 // as base64 encoded characters. ( 60 chars on each row)
41 public void EncodeStream( Stream ins
, Stream outs
) {
43 if( ( ins
== null ) || ( outs
== null ) )
44 throw new ArgumentNullException( "The input and output streams may not " +
47 ICryptoTransform base64
= new ToBase64Transform();
50 byte[] plainText
= new byte[ base64
.InputBlockSize
];
51 byte[] cipherText
= new byte[ base64
.OutputBlockSize
];
55 byte[] newln
= new byte[] { 13 , 10 }
; //CR LF with mail
57 // read through the stream until there
58 // are no more bytes left
62 readLength
= ins
.Read( plainText
, 0 , plainText
.Length
);
64 // break when there is no more data
65 if( readLength
< 1 ) break;
67 // transfrom and write the blocks. If the block size
68 // is less than the InputBlockSize then write the final block
69 if( readLength
== plainText
.Length
) {
71 base64
.TransformBlock( plainText
, 0 ,
76 outs
.Write( cipherText
, 0 , cipherText
.Length
);
79 // do this to output lines that
81 count
+= cipherText
.Length
;
83 outs
.Write( newln
, 0 , newln
.Length
);
89 // convert the final blocks of bytes and write them
90 cipherText
= base64
.TransformFinalBlock( plainText
, 0 , readLength
);
91 outs
.Write( cipherText
, 0 , cipherText
.Length
);
97 outs
.Write( newln
, 0 , newln
.Length
);