Click here to Skip to main content
14,424,238 members

Base64 Decoder and Encoder

Rate this:
2.96 (17 votes)
Please Sign up or sign in to vote.
2.96 (17 votes)
28 Feb 2010CPOL
Sample code for encoding and decoding Base64 data
Screenshot - screenshot.gif


I got interested in decoding from base64 due to an e-mail that I received that had gotten reformatted and the attached images were only visible as base64 strings.

Being an exceptionally inquisitive person, I wanted to know what the file attachments contained. I am by no means an expert programmer, but I thought it would be an adventure to try and convert the data. I found (on this very site) sample code (in C#) for converting strings to and from base64. Because the image's base64 string was too long, I adapted the code to read the string from a file and write the converted string to a file. This didn't seem to work at all as some of the characters weren't converted correctly. It converted simple strings, but nothing too advanced.

I had a further look on the net and there are many products out there that will do all this for you - but at a price. I realized that I would probably have to do this by myself. I had a quick look under the hood of Framework 2.0 and, to my pleasant surprise, the good folks at Microsoft had done all the hard work for me. All I had to do was slap some lines of code down and it worked like a dream. This is nothing fancy, but it does what it is supposed to do: encode to and decode from Base64.

Using the Code

The basic methods used in this code are System.Convert.ToBase64String (encoding) and System.Convert.FromBase64String (decoding).

We start off with an image which has been Base64 encoded - probably by someone out to ruin your day. I have encoded, for your pleasure, a simple image file (this file is also available in the source code and it is titled -aptly - encoded.txt).


Your inquisitive nature now wants to know what the picture contains. To do this, you use this simple code:

Public Class Form1

    Sub DecodeFile(ByVal srcFile As String, ByVal destFile As String)
        Dim src As String
        Dim sr As New IO.StreamReader(srcFile)

        src = sr.ReadToEnd


        Dim bt64 As Byte() = System.Convert.FromBase64String(src)

        If IO.File.Exists(destFile) Then
        End If

        Dim sw As New IO.FileStream(destFile, IO.FileMode.Create)

        sw.Write(bt64, 0, bt64.Length)


    End Sub

    Sub EncodeFile(ByVal srcFile As String, ByVal destfile As String)
        Dim srcBT As Byte()
        Dim dest As String

        Dim sr As New IO.FileStream(srcFile, IO.FileMode.Open)

        ReDim srcBT(sr.Length)

        sr.Read(srcBT, 0, sr.Length)


        dest = System.Convert.ToBase64String(srcBT)

        Dim sw As New IO.StreamWriter(destfile, False)



    End Sub

    Private Sub butBrowseDec_Click(ByVal sender As System.Object, _
	ByVal e As System.EventArgs) Handles butBrowseDec.Click

        Me.txtDecoded.Text = Me.SaveFileDialog1.FileName

    End Sub

    Private Sub butBrowse_Click(ByVal sender As System.Object, _
	ByVal e As System.EventArgs) Handles butBrowse.Click

        Me.txtEncoded.Text = Me.SaveFileDialog1.FileName
    End Sub

    Private Sub butEndcode_Click(ByVal sender As System.Object, _
	ByVal e As System.EventArgs) Handles butEndcode.Click
            If Me.txtDecoded.Text = Nothing Or Me.txtEncoded.Text = Nothing Then
                MsgBox("Please select source and destination files!")
                Exit Sub
            End If

            Me.EncodeFile(Me.txtDecoded.Text, Me.txtEncoded.Text)

            MsgBox("Conversion complete!")

        Catch ex As Exception

        End Try

    End Sub

    Private Sub butDecode_Click(ByVal sender As System.Object, _
	ByVal e As System.EventArgs) Handles butDecode.Click
            If Me.txtDecoded.Text = Nothing Or Me.txtEncoded.Text = Nothing Then
                MsgBox("Please select source and destination files!")
                Exit Sub
            End If

            Me.DecodeFile(Me.txtEncoded.Text, Me.txtDecoded.Text)

            MsgBox("Conversion complete!")

        Catch ex As Exception

        End Try

    End Sub
End Class

As you will see above, I didn't need to write anything fancy - the Framework has all the clever stuff already included. All you need to do is lay it out right. Using the code provided, you can easily encode and decode simple strings using the provided textboxes, but when it comes to files - even the encoded string I included - it simply doesn't display the result in the decoded box. So I needed to include file handling capabilities.

To make sure that your application works:

  1. Copy the encrypted string to a text file and save
  2. Run the application and select the file in the "encoded" file location text box
  3. Enter a filename into the "decoded" file location box and give it a ".gif" extension

Click on the decode button between the file location textboxes. If you can open the image file, you have succeeded in converting a Base64 string into an Image file.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Eugene van der Walt
Web Developer
South Africa South Africa
Born. School. 2 Law degrees and i dumped them for a job as a develper because technology is my passion.

Comments and Discussions

QuestionOther Example for testing Pin
Member 108718544-Feb-17 4:01
MemberMember 108718544-Feb-17 4:01 
GeneralMy vote of 4 Pin
Tanmoy_Mazumder11-Mar-13 1:49
MemberTanmoy_Mazumder11-Mar-13 1:49 
QuestionGood but one small mistake Pin
maurolo25-Apr-12 23:42
Membermaurolo25-Apr-12 23:42 
GeneralMy vote of 5 Pin
bebopperz17-Feb-11 13:21
Memberbebopperz17-Feb-11 13:21 
Questionthanks and need more help Pin
skyfriendly3-Aug-10 3:33
Memberskyfriendly3-Aug-10 3:33 
GeneralMy vote of 1 Pin
GurliGebis28-Feb-10 3:38
MemberGurliGebis28-Feb-10 3:38 
GeneralRe: My vote of 1 Pin
bebopperz17-Feb-11 13:20
Memberbebopperz17-Feb-11 13:20 
GeneralThank you ! Pin
quake33325-Feb-10 3:18
Memberquake33325-Feb-10 3:18 
Questionso much extra code for nothing? Pin
ii_noname_ii10-Feb-09 2:39
Memberii_noname_ii10-Feb-09 2:39 
AnswerRe: so much extra code for nothing? Pin
ii_noname_ii10-Feb-09 2:52
Memberii_noname_ii10-Feb-09 2:52 
QuestionAny size limit for the file needed to be encoded? Pin
platelet15-Jan-09 11:13
Memberplatelet15-Jan-09 11:13 
GeneralI will tell you why the framework to not have your function... Pin
Jcmorin20-Apr-07 6:49
MemberJcmorin20-Apr-07 6:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Posted 19 Apr 2007


47 bookmarked