Introduction

This article explains the following:

Database

Use the following table and Stored Procedure to demonstrate this concept.

Table

Use the following script to create the preceding table.

  1. CREATE table FileDetails
  2. (
  3. FileId int Primary Key Identity(1,1),
  4. FileName varchar(100),
  5. FileSize varchar(30),
  6. FileType varchar(30),
  7. FilePath varchar(200),
  8. CreatedOn Datetime
  9. )
  10. Use the following script to Create the Stored procedures
  11. --To get all File Details
  12. CREATE procedure USP_Select_FileDetails
  13. AS
  14. Begin
  15. Select * from FileDetails
  16. END
  17. --To Insert File Details
  18. CREATE procedure USP_Insert_FileDetails
  19. @FileName varchar(100),
  20. @FileSize varchar(30),
  21. @FileType varchar(30),
  22. @FilePath varchar(200),
  23. @CreatedOn Datetime = Null
  24. AS
  25. Begin
  26. Insert FileDetails(FileName,FileSize,FileType,FilePath,CreatedOn)
  27. Values(@FileName,@FileSize,@FileType,@FilePath,GetDate())
  28. END

Creating the project

Now create the project using the following.

Go to Start, then All Programs and click Microsoft Visual Studio 2010
Go to File, then click New, Project..., Visual C# , Web. Then select ASP.NET Empty Web Application.

Provide the project a name and specify the location.

Empty Web Application


Web.Config

Create the connection string in the Web.Config file as in the following code snippet:

  1. <connectionStrings>
  2. <add name="conStr"
  3. connectionString="Password= 1234; User ID=sa; Database=DB_Jai; Data Source=."
  4. providerName="System.Data.SqlClient"/>
  5. </connectionStrings>

Next: Right-click on Solution Explorer and add a web form to your project.

Webform Design

Design you Webform (.aspx page) as in the following:

  1. <div align="center" style="width: 100%;">
  2. <fieldset style="width: 30%;">
  3. <legend>Download Files From GridView</legend>
  4. <table width="100%">
  5. <tr>
  6. <td align="left">
  7. <asp:FileUpload ID="FileUpload1" runat="server" />
  8. </td>
  9. <td align="left">
  10. <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
  11. </td>
  12. </tr>
  13. <tr>
  14. <td colspan="2" align="center">
  15. <br />
  16. <asp:Label ID="lblMsg" runat="server" ></asp:Label>
  17. </td>
  18. <tr>
  19. <td colspan="2" align="center">
  20. <br />
  21. <asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="False" Width="100%"
  22. OnRowCommand="gvFiles_RowCommand">
  23. <Columns>
  24. <asp:TemplateField HeaderText="Download Here">
  25. <ItemTemplate>
  26. <asp:LinkButton ID="lnkDownload" runat="server" CausesValidation="False" CommandArgument='<%# Eval("FileName") %>'
  27. CommandName="Download" Text='<%# Eval("FileName") %>' />
  28. </ItemTemplate>
  29. </asp:TemplateField>
  30. <asp:BoundField DataField="FileSize" HeaderText="File Size" />
  31. <asp:BoundField DataField="FileType" HeaderText="File Type" />
  32. </Columns>
  33. </asp:GridView>
  34. </td>
  35. </tr>
  36. </table>
  37. </fieldset>
  38. </div>
CodeBehind

Add the following namespaces:
  1. using System.Data;
  2. using System.IO;
  3. using System.Data.SqlClient;
  4. using System.Configuration;
  5. using System.Drawing;
Invoke the ConnectionString from Web.Config as in the following:
  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);
User Defined Functions

#region User Defined Methods
  1. //Get file type by Extension
  2. private string GetFileExtension(string fileExtension)
  3. {
  4. switch (fileExtension.ToLower())
  5. {
  6. case ".docx":
  7. case ".doc":
  8. return "Microsoft Word Document";
  9. case ".xlsx":
  10. case ".xls":
  11. return "Microsoft Excel Document";
  12. case ".txt":
  13. return "Text Document";
  14. case ".jpg":
  15. case ".png":
  16. return "Image";
  17. default:
  18. return "Unknown";
  19. }
  20. }
  21. //Save File in folder and File details and Path to database
  22. private void UploadFile()
  23. {
  24. string FileName = string.Empty;
  25. string FileSize = string.Empty;
  26. string extension = string.Empty;
  27. string FilePath = string.Empty;
  28. if (FileUpload1.HasFile)
  29. {
  30. extension = Path.GetExtension(FileUpload1.FileName);
  31. FileName = FileUpload1.PostedFile.FileName;
  32. FileSize = FileName.Length.ToString() + " Bytes";
  33. //strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + FileUpload1.FileName;
  34. FileUpload1.PostedFile.SaveAs(Server.MapPath(@"~/Application/FileUploads/" + FileName.Trim()));
  35. FilePath = @"~/Application/FileUploads/" + FileName.Trim().ToString();
  36. }
  37. else
  38. {
  39. lblMsg.Text = "Plase upload the file";
  40. lblMsg.ForeColor = Color.Red;
  41. return;
  42. }
  43. SqlCommand cmd = new SqlCommand("USP_Insert_FileDetails", con);
  44. cmd.CommandType = System.Data.CommandType.StoredProcedure;
  45. cmd.Parameters.AddWithValue("@FileName", FileName);
  46. cmd.Parameters.AddWithValue("@FileSize", FileSize);
  47. cmd.Parameters.AddWithValue("@FileType", GetFileExtension(extension));
  48. cmd.Parameters.AddWithValue("@FilePath", FilePath);
  49. con.Open();
  50. int result = cmd.ExecuteNonQuery();
  51. if (result > 0)
  52. {
  53. lblMsg.Text = "File Uploaded Successfully ";
  54. lblMsg.ForeColor = Color.Green;
  55. BindGridView();
  56. }
  57. }
  58. //Displaying the list of files in GridView that are already uploaded
  59. private void BindGridView()
  60. {
  61. SqlDataAdapter adp = new SqlDataAdapter("USP_Select_FileDetails", con);
  62. adp.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
  63. if (con.State != ConnectionState.Open)
  64. {
  65. con.Open();
  66. }
  67. DataSet ds = new DataSet();
  68. adp.Fill(ds);
  69. gvFiles.DataSource = ds;
  70. gvFiles.DataBind();
  71. }
Page Event Handlers

#region Page Event Handlers.
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. lblMsg.Text = string.Empty;
  4. if (!Page.IsPostBack)
  5. {
  6. BindGridView();
  7. }
  8. }
  9. protected void btnUpload_Click(object sender, EventArgs e)
  10. {
  11. UploadFile();
  12. }
  13. protected void gvFiles_RowCommand(object sender, GridViewCommandEventArgs e)
  14. {
  15. Response.Clear();
  16. Response.ContentType = "application/octet-stream";
  17. Response.AppendHeader("Content-Disposition", "filename=" + e.CommandArgument);
  18. Response.TransmitFile(Server.MapPath("~/Application/FileUploads/") + e.CommandArgument);
  19. Response.End();
  20. }
#endregion

Output

Upload the file using file upload control and click on the Upload button. The uploaded file is displayed in the GridView. Next click on the link button to download the files.

GridView

I hope you enjoyed this article. Please provide your valuable suggestions and feedback.