In this article I will explain with an example, how to convert (save) Byte Array as File in ASP.Net using C# and VB.Net.
The Byte Array will be converted (saved) as File using the File class in C# and VB.Net.
 
 
HTML Markup
The following HTML Markup consists of an ASP.Net FileUpload control, a Button and an Image control.
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload"
    onclick="btnUpload_Click" />
<hr />
<asp:Image ID="Image1" Visible = "false" runat="server" Height = "100" Width = "100" />
 
 
Namespaces
You will need to import the following namespace.
C#
using System.IO;
 
VB.Net
Imports System.IO
 
 
Convert (Save) Byte Array as File 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 saved to a folder as file using the WriteAllBytes method of the File class.
Finally the Base64 encoded string is displayed on web page as Image using Image control.
C#
protected void btnUpload_Click(object sender, EventArgs e)
{
    //Read the uploaded File as Byte Array from FileUpload control.
    Stream fs = FileUpload1.PostedFile.InputStream;
    BinaryReader br = new BinaryReader(fs);
    byte[] bytes = br.ReadBytes((Int32)fs.Length);
 
    //Save the Byte Array as File.
    string filePath = "~/Files/" + Path.GetFileName(FileUpload1.FileName);
    File.WriteAllBytes(Server.MapPath(filePath), bytes);
 
    //Display the Image File.
    Image1.ImageUrl = filePath;
    Image1.Visible = true;
}
 
VB.Net
Protected Sub btnUpload_Click(sender As Object, e As EventArgs)
    'Read the uploaded File as Byte Array from FileUpload control.
    Dim fs As Stream = FileUpload1.PostedFile.InputStream
    Dim br As New BinaryReader(fs)
    Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fs.Length))
 
    'Save the Byte Array as File.
    Dim filePath As String = "~/Files/" + Path.GetFileName(FileUpload1.FileName)
    File.WriteAllBytes(Server.MapPath(filePath), bytes)
 
    'Display the Image File.
    Image1.ImageUrl = filePath
    Image1.Visible = True
End Sub
 
 
Demo
 
 
Downloads
Download Code