-->

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.

  1. namespace ASPEncryptDecryptFile
  2. {
  3. public class UploadFile
  4. {
  5. public string FileName { get; set; }
  6. public string FileExtention { get; set; }
  7. public long Size { get; set; }
  8. public string FilePath { get; set; }
  9. public string ICon { get; set; }
  10. }
  11. }

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

  1. <h3>File Upload with encryption and Download with decryption using ASP.NET C#. </h3>
  2. <div>
  3. <table>
  4. <tr>
  5. <td>Select File : </td>
  6. <td>
  7. <asp:FileUpload ID="FileUpload1" runat="server" /></td>
  8. <td>
  9. <asp:Button ID="btnUpload" runat="server" Text="Upload & Encrypt" OnClick="btnUpload_Click" /></td>
  10. </tr>
  11. </table>
  12. <div>
  13. <%-- Add Datalist for Show Uploaded Files --%>
  14. <asp:DataList ID="DataList1" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemCommand="DataList1_ItemCommand">
  15. <ItemTemplate>
  16. <table>
  17. <tr>
  18. <td>
  19. <img src='<%#Eval("ICon") %>' width="60px" />
  20. </td>
  21. </tr>
  22. <tr>
  23. <td>
  24. <%#Eval("FileName") %>
  25. </td>
  26. </tr>
  27. <tr>
  28. <td>
  29. <%#Eval("Size","{0} KB") %>
  30. </td>
  31. </tr>
  32. <tr>
  33. <td>
  34. <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%#Eval("FilePath") %>'>Download</asp:LinkButton>
  35. </td>
  36. </tr>
  37. </table>
  38. </ItemTemplate>
  39. </asp:DataList>
  40. </div>
  41. </div>

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

Write below code into Page_Load event for show uploaded files.

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. {
  5. PopulateUploadedFiles();
  6. }
  7. }

   And here is the function PopulateUploadedFiles

  1. private void PopulateUploadedFiles()
  2. {
  3. DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/UploadedFiles"));
  4. List<UploadFile> uploadedFiles = new List<UploadFile>();
  5. foreach (var file in di.GetFiles())
  6. {
  7. uploadedFiles.Add
  8. (
  9. new UploadFile
  10. {
  11. FileName = file.Name,
  12. FileExtention = Path.GetExtension(file.Name),
  13. FilePath = file.FullName,
  14. Size = (file.Length/1024), // For get size in KB
  15. ICon = GetIconPath(Path.GetExtension(file.FullName)) // Need to Get Icon...
  16. }
  17. );
  18. }
  19.  
  20. DataList1.DataSource = uploadedFiles;
  21. DataList1.DataBind();
  22. }

   And function GetIconPath for Icon path.

  1. private string GetIconPath(string fileExtention)
  2. {
  3. string Iconpath = "/Images";
  4. string ext = fileExtention.ToLower();
  5. switch (ext)
  6. {
  7. case ".txt":
  8. Iconpath += "/txt.png";
  9. break;
  10. case ".doc":
  11. case ".docx":
  12. Iconpath += "/word.png";
  13. break;
  14. case ".xls":
  15. case ".xlsx":
  16. Iconpath += "/xls.png";
  17. break;
  18. case ".pdf":
  19. Iconpath += "/pdf.png";
  20. break;
  21. case ".rar":
  22. Iconpath += "/rar.png";
  23. break;
  24. case ".zip":
  25. case ".7z":
  26. Iconpath += "/zip.png";
  27. break;
  28. default:
  29. break;
  30. }
  31. return Iconpath;
  32. }

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

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

  1. protected void btnUpload_Click(object sender, EventArgs e)
  2. {
  3. // Add code to upload file with encryption
  4.  
  5. byte[] file = new byte[FileUpload1.PostedFile.ContentLength];
  6. FileUpload1.PostedFile.InputStream.Read(file, 0, FileUpload1.PostedFile.ContentLength);
  7.  
  8. string fileName = FileUpload1.PostedFile.FileName;
  9.  
  10. // key for encryption
  11. byte[] Key = Encoding.UTF8.GetBytes("asdf!@#$1234ASDF");
  12. try
  13. {
  14. string outputFile = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
  15. if (File.Exists(outputFile))
  16. {
  17. // Show Already exist Message
  18. }
  19. else
  20. {
  21. FileStream fs = new FileStream(outputFile, FileMode.Create);
  22. RijndaelManaged rmCryp = new RijndaelManaged();
  23. CryptoStream cs = new CryptoStream(fs, rmCryp.CreateEncryptor(Key, Key), CryptoStreamMode.Write);
  24. foreach (var data in file)
  25. {
  26. cs.WriteByte((byte)data);
  27. }
  28. cs.Close();
  29. fs.Close();
  30. }
  31.  
  32. PopulateUploadedFiles();
  33. }
  34. catch
  35. {
  36. Response.Write("Encryption Failed! Please try again.");
  37. }
  38. }

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

Write below code into DataList1_ItemCommand event for Download decrypted file.

  1. protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
  2. {
  3. if (e.CommandName == "Download")
  4. {
  5. string filePath = e.CommandArgument.ToString();
  6. // key for decryption
  7. byte[] Key = Encoding.UTF8.GetBytes("asdf!@#$1234ASDF");
  8.  
  9. //UnicodeEncoding ue = new UnicodeEncoding();
  10. FileStream fs = new FileStream(filePath, FileMode.Open);
  11. RijndaelManaged rmCryp = new RijndaelManaged();
  12. CryptoStream cs = new CryptoStream(fs, rmCryp.CreateDecryptor(Key, Key), CryptoStreamMode.Read);
  13. try
  14. {
  15. // Decrypt & Download Here
  16. Response.ContentType = "application/octet-stream";
  17. //Response.AddHeader("Content-Disposition","attachment; filename=" + Path.GetFileName(filePath) + Path.GetExtension(filePath));
  18. Response.AddHeader("Content-Disposition", "attachment; filename=myfile" + Path.GetExtension(filePath));
  19. int data;
  20. while ((data = cs.ReadByte()) != -1)
  21. {
  22. Response.OutputStream.WriteByte((byte)data);
  23. Response.Flush();
  24. }
  25. cs.Close();
  26. fs.Close();
  27. }
  28. catch (Exception ex)
  29. {
  30. Response.Write(ex.Message);
  31. }
  32. finally
  33. {
  34. cs.Close();
  35. fs.Close();
  36. }
  37. }
  38. }

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.

Related Posts: