How to decode a base64 string in VB.NET

Sometimes, we receive an e-mail that we can’t really open directly, but we have the base64 source.

I may receive an attached EML file, that is, an outlook express email attached with another e-mail.  I have all the original source of this file, but I do not have Outlook Express installed.  I created a really simple decoder and it work fine.  You just have to look at the boundary of your email.  Find the beginning of attachment by searching for « filename= » and you’ll have the filename of the attached file.  Then, copy the following code, all the « binary string » code, and only this, without the leading MIME informations, to a text file.  In my sample, I called it « c:base64.txt ».  Then, I saw that the filename is a pdf.  I choose « c:base64.pdf » as my output.  This is the code you can use to decode a base64 attachment.

   Dim bytes() As Byte
   Dim reader As New System.IO.StreamReader("c:base64.txt")
   Dim str As String = reader.ReadToEnd
   bytes = System.Convert.FromBase64String(str)
   Dim writer As New System.IO.BinaryWriter(IO.File.Open("c:base64.pdf", IO.FileMode.Create))
That’s all!