Base64 Encode or Decode a File


/ Published in: C#
Save to your folder(s)

Useful for sending files past filters via email.


Copy this code and paste it in your HTML
  1. private void btnEncode_Click(object sender, EventArgs e)
  2. {
  3. if (!string.IsNullOrEmpty(txtInFile.Text))
  4. {
  5. FileStream fs = new FileStream(txtInFile.Text,
  6. FileMode.Open,
  7. FileAccess.Read);
  8. byte[] filebytes = new byte[fs.Length];
  9. fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
  10. string encodedData =
  11. Convert.ToBase64String(filebytes,
  12. Base64FormattingOptions.InsertLineBreaks);
  13. txtEncoded.Text = encodedData;
  14. }
  15. }
  16.  
  17. private void btnDecode_Click(object sender, EventArgs e)
  18. {
  19. if (!string.IsNullOrEmpty(txtOutFile.Text))
  20. {
  21. byte[] filebytes = Convert.FromBase64String(txtEncoded.Text);
  22. FileStream fs = new FileStream(txtOutFile.Text,
  23. FileMode.CreateNew,
  24. FileAccess.Write,
  25. FileShare.None);
  26. fs.Write(filebytes, 0, filebytes.Length);
  27. fs.Close();
  28. }
  29. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.