How to download file Using ASP.Net with C# - ASP TANMOY

Latest

Wednesday, 25 December 2013

How to download file Using ASP.Net with C#



Description:
Most of websites provides an option to download documents or files like download notification, download advertisement, download video, and download music. In my previous post I have explain how to upload files to server. Today I am explaining how to download uploaded files. There are various methods but I am explaining the easiest way to download file. When we click the download button then Internet download manager or any other downloader will capture the link and start download. One example has given to the following image.

 

 


Step1:
Suppose we have already design the database like



 

This database will content id of the file, file name and file link. 

 


Step2:
Create two empty webpage. One page will redirect the session ID of the file. Take a hyperlink to the second webpage. Set some properties of the hyperlink for nice look and You must set the target property blank.
Target="_blank"



Add two Names Spaces
1. using System.Data;
2. using System.Data.SqlClient;




Step3:

Write the following code


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;


public partial class downloadFile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["fileid"] = "20";// Say,this id has transfer from the previous page
        SqlConnection con = new SqlConnection("Your Database connection.”);
        SqlCommand com = new SqlCommand("select fileLink from FileUpload where ID=@var1", con);
        com.Parameters.Add("@var1", SqlDbType.NVarChar);
        com.Parameters["@var1"].Value = Session["fileid"].ToString();
        con.Open();
        object fileObj = com.ExecuteScalar();

        string filelink = fileObj.ToString();
        HyperLink1.NavigateUrl = "../"+filelink.ToString();
        con.Close();

    }
}




Note:

This Code can Show an error “The resource cannot be found.” Or “404 Server Error” On your local Machine. If you want to run it on local machine then you have to provide your resource path to the hyperlink before add the file link. For example  if you want to run this project then hyperlink navigation url will be

HyperLink1.NavigateUrl = "(your project folder link)"+filelink.ToString();

The best option is that you need not change the code. This project will fully work on web server because this code automatically find your folder of the server. The download URL will look like

HyperLink1.NavigateUrl = “www.example.com/Files/Accenture.docx

So. Upload the project to your web server and enjoy.

 



Download Code

No comments:

Post a Comment