code_junkie

Base64 Encode a PDF in C#

Nov 13th, 2011
520
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. class Base64Encoder
  2. {
  3. public void Encode(string inFileName, string outFileName)
  4. {
  5. System.Security.Cryptography.ICryptoTransform transform = new System.Security.Cryptography.ToBase64Transform();
  6. using(System.IO.FileStream inFile = System.IO.File.OpenRead(inFileName),
  7. outFile = System.IO.File.Create(outFileName))
  8. using (System.Security.Cryptography.CryptoStream cryptStream = new System.Security.Cryptography.CryptoStream(outFile, transform, System.Security.Cryptography.CryptoStreamMode.Write))
  9. {
  10. // I'm going to use a 4k buffer, tune this as needed
  11. byte[] buffer = new byte[4096];
  12. int bytesRead;
  13.  
  14. while ((bytesRead = inFile.Read(buffer, 0, buffer.Length)) > 0)
  15. cryptStream.Write(buffer, 0, bytesRead);
  16.  
  17. cryptStream.FlushFinalBlock();
  18. }
  19. }
  20.  
  21. public void Decode(string inFileName, string outFileName)
  22. {
  23. System.Security.Cryptography.ICryptoTransform transform = new System.Security.Cryptography.FromBase64Transform();
  24. using (System.IO.FileStream inFile = System.IO.File.OpenRead(inFileName),
  25. outFile = System.IO.File.Create(outFileName))
  26. using (System.Security.Cryptography.CryptoStream cryptStream = new System.Security.Cryptography.CryptoStream(inFile, transform, System.Security.Cryptography.CryptoStreamMode.Read))
  27. {
  28. byte[] buffer = new byte[4096];
  29. int bytesRead;
  30.  
  31. while ((bytesRead = cryptStream.Read(buffer, 0, buffer.Length)) > 0)
  32. outFile.Write(buffer, 0, bytesRead);
  33.  
  34. outFile.Flush();
  35. }
  36. }
  37.  
  38. // this version of Encode pulls everything into memory at once
  39. // you can compare the output of my Encode method above to the output of this one
  40. // the output should be identical, but the crytostream version
  41. // will use way less memory on a large file than this version.
  42. public void MemoryEncode(string inFileName, string outFileName)
  43. {
  44. byte[] bytes = System.IO.File.ReadAllBytes(inFileName);
  45. System.IO.File.WriteAllText(outFileName, System.Convert.ToBase64String(bytes));
  46. }
  47. }
Add Comment
Please, Sign In to add comment