In this article I will explain with an example, how to convert Base64 string to Byte Array using C# and VB.Net.
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net FileUpload control to upload the Image File and a Button control to trigger the File upload process.
<form id="form1" runat="server">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
    onclick="btnUpload_Click" />
</form>
 
 
Convert Base64 string to Byte Array using C# and VB.Net
When the Upload button is clicked, the Image file is read into a Byte Array using the BinaryReader class object.
The Byte Array is then converted into Base64 encoded string using the Convert.ToBase64String method.
Now in order to save the Base64 encoded string as Image File, the Base64 encoded string is converted back to Byte Array using the Convert.FromBase64String function.
Finally the Byte Array is saved to Folder on Disk as File using WriteAllBytes method of the File class.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
    //***Convert Image File to Base64 Encoded string***//
 
    //Read the uploaded file using BinaryReader and convert it to Byte Array.
    BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream);
    byte[] bytes = br.ReadBytes((int)FileUpload1.PostedFile.InputStream.Length);
 
    //Convert the Byte Array to Base64 Encoded string.
    string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
 
    //***Save Base64 Encoded string as Image File***//
 
    //Convert Base64 Encoded string to Byte Array.
    byte[] imageBytes = Convert.FromBase64String(base64String);
       
    //Save the Byte Array as Image File.
    string filePath = Server.MapPath("~/Files/" + Path.GetFileName(FileUpload1.PostedFile.FileName));
    File.WriteAllBytes(filePath, imageBytes);
}
 
VB.Net
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
    '***Convert Image File to Base64 Encoded string***
 
    'Read the uploaded file using BinaryReader and convert it to Byte Array.
    Dim br As New BinaryReader(FileUpload1.PostedFile.InputStream)
    Dim bytes As Byte() = br.ReadBytes(CInt(FileUpload1.PostedFile.InputStream.Length))
 
    'Convert the Byte Array to Base64 Encoded string.
    Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
 
    '***Save Base64 Encoded string as Image File***
 
    'Convert Base64 Encoded string to Byte Array.
    Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
 
    'Save the Byte Array as Image File.
    Dim filePath As String = Server.MapPath("~/Files/" + Path.GetFileName(FileUpload1.PostedFile.FileName))
    File.WriteAllBytes(filePath, imageBytes)
End Sub
 
 
Downloads