c
.Net For Beginner
File Upload and Download ASP.NET C#
This article is for how to upload and download files using ASP.NET.



Create a new project and add new .aspx page to that for file upload function(FileUpload.aspx).

The design of FileUpload.aspx page is given above.

Add a new .cs file for database FILEDB(which is used store the subject,university details).

FILEDB.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace FileUploadDownload
{
    public class FILEDB :DbContext 
    {
        public DbSet<QuestionPaper> QuestionPaper { get; set; }
       
    }
}

QuestionPaper.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace FileUploadDownload
{
    public class QuestionPaper
    {
        [Key]
        public virtual int Id { get; set; }
        [Required]
        public virtual String Subject { get; set; }
        public virtual String University { get; set; }
        public virtual String QuestionPaperUrl { get; set; }
    }
}
Add the given below 'FileUpload' code in the 'Submit' button click event.The uploaded files are stored in a Folder(UploadedFiles).

_DB.QuestionPaper.Add(new QuestionPaper() { University = txtUniversity.Text, Subject = txtSubject.Text });

                _DB.SaveChanges();

                int Id = (from a in _DB.QuestionPaper

                          select a.Id).Max();

                string extension = Path.GetExtension(FileUpload2.PostedFile.FileName);
               

                if (System.IO.File.Exists("UploadedFiles/" + Id + extension))
                    System.IO.File.Delete("UploadedFiles/" + Id + extension);
                FileUpload2.SaveAs(Server.MapPath("UploadedFiles/" + Id+extension));
                string path2 = string.Format("{0}/{1}{2}", "UploadedFiles", Id, extension);
                var x = _DB.QuestionPaper.Single(r => r.Id == Id);
                x.QuestionPaperUrl = path2;
                _DB.SaveChanges();

FileUpload.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;

namespace FileUploadDownload
{
    public partial class FileUpload : System.Web.UI.Page
    {
        FILEDB _DB = new FILEDB();
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            _DB.QuestionPaper.Add(new QuestionPaper() { University = txtUniversity.Text, Subject = txtSubject.Text });

                _DB.SaveChanges();

                int Id = (from a in _DB.QuestionPaper

                          select a.Id).Max();

                string extension = Path.GetExtension(FileUpload2.PostedFile.FileName);
               

                if (System.IO.File.Exists("UploadedFiles/" + Id + extension))
                    System.IO.File.Delete("UploadedFiles/" + Id + extension);
                FileUpload2.SaveAs(Server.MapPath("UploadedFiles/" + Id+extension));
                string path2 = string.Format("{0}/{1}{2}", "UploadedFiles", Id, extension);
                var x = _DB.QuestionPaper.Single(r => r.Id == Id);
                x.QuestionPaperUrl = path2;
                _DB.SaveChanges();
           
        }

    }
}
Add .aspx page for file download(FileDownload.aspx)

FileDownload.aspx


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="FileDownload.aspx.cs" Inherits="FileUploadDownload.WebForm2" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<asp:GridView ID="gridDownload" CssClass="Gridview" runat="server" AutoGenerateColumns="false" DataKeyNames="QuestionPaperUrl">
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Subject" HeaderText="Subject" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Content>

Code behind FileDownload.aspx


Add the following codes in About.aspx.cs

FileDownload.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace FileUploadDownload
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                gridDownload.DataSource = GetData();
                gridDownload.DataBind();
            }
        }
        DataTable GetData()
        {
            DataTable dt = new DataTable();
            string con = ConfigurationManager.ConnectionStrings["FILEDB"].ToString();
            SqlConnection conn = new SqlConnection(con);
            conn.Open();
            SqlCommand cmd = new SqlCommand("select * from QuestionPaper ", conn);
            SqlDataAdapter adpt = new SqlDataAdapter(cmd);
            adpt.Fill(dt);
            return dt;
        }
        protected void lnkDownload_Click(object sender, EventArgs e)
        {
            LinkButton lnkbtn = sender as LinkButton;
            GridViewRow row = lnkbtn.NamingContainer as GridViewRow;
            string filePath = gridDownload.DataKeys[row.RowIndex].Value.ToString();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
            Response.TransmitFile(Server.MapPath(filePath));
            Response.End();
        }
    }
}
Run the project










                       DOWNLOAD SOURCE CODE 

FileUploadDownload.zip