-->

How to upload file with encryption and download file with decryption using asp.net c#?

Introduction

In this post I am explain how to upload file with encryption and download file with decryption using asp.net c#?

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add New Folder.

Right Click on Solution Explorer > Add > New Folder > Rename Folder.

Step-3: Add a Class.

Right Click on Solution Explorer > Add > Class > Enter Class Name > Add.
Here is the class.

            namespace ASPEncryptDecryptFile
            {
                public class UploadFile
                {
                    public string FileName { get; set; }
                    public string FileExtention { get; set; }
                    public long Size { get; set; }
                    public string FilePath { get; set; }
                    public string ICon { get; set; }
                }
            }
        

Step-4: Add a Webpage and Design for upload file with encryption & show in datalist.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

HTML Code

    <h3>File Upload with encryption and Download with decryption using ASP.NET C#. </h3>
    <div>
        <table>
            <tr>
                <td>Select File : </td>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" /></td>
                <td>
                    <asp:Button ID="btnUpload" runat="server" Text="Upload & Encrypt" OnClick="btnUpload_Click" /></td>
            </tr>
        </table>
        <div>
            <%-- Add Datalist for Show Uploaded Files --%>
            <asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemCommand="DataList1_ItemCommand">
                <ItemTemplate>
                    <table>
                        <tr>
                            <td>
                                <img src='<%#Eval("ICon") %>' width="60px" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%#Eval("FileName") %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <%#Eval("Size","{0} KB") %>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%#Eval("FilePath") %>'>Download</asp:LinkButton>
                            </td>
                        </tr>
                    </table>
                </ItemTemplate>
            </asp:DataList>
        </div>
    </div>
        

Step-5: Write code into page load event for show data.

Write below code into Page_Load event for show uploaded files.

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateUploadedFiles();
            }
        }
        

   And here is the function PopulateUploadedFiles

         private void PopulateUploadedFiles()
        {
            DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/UploadedFiles"));
            List<UploadFile> uploadedFiles = new List<UploadFile>();
            foreach (var file in di.GetFiles())
            {
                uploadedFiles.Add
                (
                    new UploadFile
                    {
                         FileName = file.Name,
                          FileExtention = Path.GetExtension(file.Name),
                           FilePath = file.FullName,
                            Size = (file.Length/1024), // For get size in KB
                             ICon = GetIconPath(Path.GetExtension(file.FullName)) // Need to Get Icon...
                    }
                );
            }

            DataList1.DataSource = uploadedFiles;
            DataList1.DataBind();
        }
        

   And function GetIconPath for Icon path.

            private string GetIconPath(string fileExtention)
        {
            string Iconpath = "/Images";
            string ext = fileExtention.ToLower();
            switch (ext)
            {
                case ".txt":
                    Iconpath += "/txt.png";
                    break;
                case ".doc":
                case ".docx":
                    Iconpath += "/word.png";
                    break;
                case ".xls":
                case ".xlsx":
                    Iconpath += "/xls.png";
                    break;
                case ".pdf":
                    Iconpath += "/pdf.png";
                    break;
                case ".rar":
                    Iconpath += "/rar.png";
                    break;
                case ".zip":
                case ".7z":
                    Iconpath += "/zip.png";
                    break;
                default:
                    break;
            }
            return Iconpath;
        }
        

Step-6: Write code for Upload file with Encryption.

Write below code into button click event for Upload file with encryption.

            protected void btnUpload_Click(object sender, EventArgs e)
        {
            // Add code to upload file with encryption

            byte[] file = new byte[FileUpload1.PostedFile.ContentLength];
            FileUpload1.PostedFile.InputStream.Read(file, 0, FileUpload1.PostedFile.ContentLength);

            string fileName = FileUpload1.PostedFile.FileName;

            // key for encryption
            byte[] Key = Encoding.UTF8.GetBytes("asdf!@#$1234ASDF");
            try
            {
                string outputFile = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
                if (File.Exists(outputFile))
                {
                    // Show Already exist Message 
                }
                else
                {
                    FileStream fs = new FileStream(outputFile, FileMode.Create);
                    RijndaelManaged rmCryp = new RijndaelManaged();
                    CryptoStream cs = new CryptoStream(fs, rmCryp.CreateEncryptor(Key, Key), CryptoStreamMode.Write);
                    foreach (var data in file)
                    {
                        cs.WriteByte((byte)data);
                    }
                    cs.Close();
                    fs.Close();
                }

                PopulateUploadedFiles();
            }
            catch 
            {
                Response.Write("Encryption Failed! Please try again.");
            }
        }
        

Step-7: Write code for Download file with decryption.

Write below code into DataList1_ItemCommand event for Download decrypted file.

            protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName == "Download")
            {
                string filePath = e.CommandArgument.ToString();
                // key for decryption
                byte[] Key = Encoding.UTF8.GetBytes("asdf!@#$1234ASDF");

                //UnicodeEncoding ue = new UnicodeEncoding();
                FileStream fs = new FileStream(filePath, FileMode.Open);
                RijndaelManaged rmCryp = new RijndaelManaged();
                CryptoStream cs = new CryptoStream(fs, rmCryp.CreateDecryptor(Key, Key), CryptoStreamMode.Read);
                try
                {
                    // Decrypt & Download Here
                    Response.ContentType = "application/octet-stream";
                    //Response.AddHeader("Content-Disposition","attachment; filename=" + Path.GetFileName(filePath) + Path.GetExtension(filePath));
                    Response.AddHeader("Content-Disposition", "attachment; filename=myfile" + Path.GetExtension(filePath));
                    int data;
                    while ((data = cs.ReadByte()) != -1)
                    {
                        Response.OutputStream.WriteByte((byte)data);
                        Response.Flush();
                        
                    }
                    cs.Close();
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
                finally
                {
                    cs.Close();
                    fs.Close();
                }
            }
        }
        

Step-8: Run Application.



Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.