Base64AttachmentEncoder.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //
  2. // System.Web.Mail.Base64AttachmentEncoder.cs
  3. //
  4. // Author(s):
  5. // Per Arneng <[email protected]>
  6. //
  7. //
  8. using System;
  9. using System.IO;
  10. using System.Text;
  11. using System.Security.Cryptography;
  12. namespace System.Web.Mail {
  13. // a class that handles Base64 encoding for attachments
  14. internal class Base64AttachmentEncoder : IAttachmentEncoder {
  15. // reads bytes from a stream and writes the encoded
  16. // as base64 encoded characters. ( 60 chars on each row)
  17. public void EncodeStream( Stream ins , Stream outs ) {
  18. if( ( ins == null ) || ( outs == null ) )
  19. throw new ArgumentNullException( "The input and output streams may not " +
  20. "be null.");
  21. ICryptoTransform base64 = new ToBase64Transform();
  22. // the buffers
  23. byte[] plainText = new byte[ base64.InputBlockSize ];
  24. byte[] cipherText = new byte[ base64.OutputBlockSize ];
  25. int readLength = 0;
  26. int trLength = 0;
  27. int count = 0;
  28. byte[] newln = new byte[] { 13 , 10 }; //CR LF with mail
  29. // read through the stream until there
  30. // are no more bytes left
  31. while( true ) {
  32. // read some bytes
  33. readLength = ins.Read( plainText , 0 , plainText.Length );
  34. // break when there is no more data
  35. if( readLength < 1 ) break;
  36. // transfrom and write the blocks. If the block size
  37. // is less than the InputBlockSize then write the final block
  38. if( readLength == plainText.Length ) {
  39. trLength = base64.TransformBlock( plainText , 0 ,
  40. plainText.Length ,
  41. cipherText , 0 );
  42. // write the data
  43. outs.Write( cipherText , 0 , cipherText.Length );
  44. // do this to output lines that
  45. // are 60 chars long
  46. count += cipherText.Length;
  47. if( count == 60 ) {
  48. outs.Write( newln , 0 , newln.Length );
  49. count = 0;
  50. }
  51. } else {
  52. // convert the final blocks of bytes and write them
  53. cipherText = base64.TransformFinalBlock( plainText , 0 , readLength );
  54. outs.Write( cipherText , 0 , cipherText.Length );
  55. }
  56. }
  57. outs.Write( newln , 0 , newln.Length );
  58. }
  59. }
  60. }