aspdotnet-suresh offers articles and tutorials,csharp dot net, articles and tutorials,VB.NET Articles,Gridview articles,code examples of 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

save/upload files in folder and download files from folder in

Feb 27, 2012

In this article I will explain how to save/upload files in folder and download files from folder system when click on link in gridview using

In many websites we will see download link whenever we click on that we will have a chance to download that files into our system.

Generally we have different ways to save files like directly in our database or our project folder. If we save files in our database it will occupy more space so it will create problem for us after host website because host providers will provide limited space for us we can solve this problem by saving files in our project folder.
Here I am going to use another post how to insert images in folder and display images from folder to implement concept like save files in folder and download those files from file system using
To implement this first design table in your database like below to save file details in database.
Column Name
Data Type
Allow Nulls
int(set identity property=true)

Now create new website after that right click on your website and add new folder and give name as Files because here I am using same name for my sample if you want to change folder name you need to change the Files folder name in your code behind also
After that design your aspx page like this

<html xmlns="">
<head runat="server">
<title>Save and Download Files from file system</title>
<style type="text/css">
background-color: Gray;
filter: alpha(opacity=80);
opacity: 0.8;
z-index: 10000;

.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-decoration:none }

<form id="form1" runat="server">
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
<asp:GridView ID="gvDetails" CssClass="Gridview" runat="server" AutoGenerateColumns="false" DataKeyNames="FilePath">
<HeaderStyle BackColor="#df5015" />
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:TemplateField HeaderText="FilePath">
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
After completion of aspx page design add the following namespaces in code behind

C# Code

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
After that write the following code in code behind

private SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
protected void Page_Load(object sender, EventArgs e)
// Bind Gridview Data
private void BindGridviewData()
SqlCommand cmd = new SqlCommand("select * from FilesTable",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
gvDetails.DataSource = ds;
// Save files to Folder and files path in database
protected void btnUpload_Click(object sender, EventArgs e)
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
SqlCommand cmd = new SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)",con);
cmd.Parameters.AddWithValue("@Name",filename );
cmd.Parameters.AddWithValue("@Path", "Files/"+filename );
// This button click event is used to download files from gridview
protected void lnkDownload_Click(object sender, EventArgs e)
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
string filePath = gvDetails.DataKeys[gvrow.RowIndex].Value.ToString();
Response.ContentType = "image/jpg";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.UI.WebControls

Partial Class Default
Inherits System.Web.UI.Page
Private con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
End If
End Sub

' Bind Gridview Data
Private Sub BindGridviewData()
Dim cmd As New SqlCommand("select * from FilesTable", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
gvDetails.DataSource = ds
End Sub

' Save files to Folder and files path in database
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim filename As String = Path.GetFileName(fileUpload1.PostedFile.FileName)
fileUpload1.SaveAs(Server.MapPath("Files/" & filename))
Dim cmd As New SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)", con)
cmd.Parameters.AddWithValue("@Name", filename)
cmd.Parameters.AddWithValue("@Path", "Files/" & filename)
End Sub

' This button click event is used to download files from gridview
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim filePath As String = gvDetails.DataKeys(gvrow.RowIndex).Value.ToString()
Response.ContentType = "image/jpg"
Response.AddHeader("Content-Disposition", "attachment;filename=""" & filePath & """")
End Sub
End Class


Download sample code attached


If you enjoyed this post, please support the blog below. It's FREE!

Get the latest,, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email


Anonymous said...

Nice aritcal is very useful to me ..Thanks..

karthic said...

super website

Anonymous said...

nice sir
you are great

Anonymous said...

Great Suresh!!!

Sunil said...

how to upload the file on ftp server and retrieve,i mean show the file in gridview with remove and download button.
please help me...

Anonymous said...

This site are very's very help full.
thanks Mr. suresh dasari

your reg red by
shamsul huda

Anonymous said...

wonderful sir

you are star

you need to make big photo of your in website

Bhaskar said...

good post .

Thanks ,

suresh gupta said...

very nice article specially those who are beginner.

muthu said...

When i upload into hosting it is not working . how to resolve this issue.please help me

Anonymous said...


jagan said...

its good for all asp .net viewers and also for beginners....

Harsh Tripathi said...

Hey Suresh,
Harsh here, Ur code is good and its very helpful. I wud suggest not to use the project folder directly, instead U can create a folder on the server and ther U can upload files, directly uploading in the project folder can lead to hacking...:-)

Suresh Dasari said...

i think that problem is because of path to folder please change the path to your hosting provider server path...

Anonymous said...

nice site for beginners

satish said...

suresh garu..
me articles really very useful in realtime..sir..

Anonymous said...

You have to allow nulls in your table for the ID or it may not work.

Joharika said...

Hi suresh,

If user click the save button in download save dialog box,i want to update the database with downloaded time,can u please help me.

cherry said...

it is working gud....but when uploading large files throwing ERROR...?

Anonymous said...

i faced exception in linkbtn coding .

Suresh Dasari said...

To solve that error you need to increase the upload size of your files in web.config check this article

bojjireddy dharmareddy said...

thank u for valuable information sharing with us

Anonymous said...

Nice work boss

Anonymous said...

really useful sort thanx.....

Anonymous said...

hi suresh....tis s bargava,ur blog is really nice and useful,and can u send me the code of upload and download the file such as,msword,pdf into sql datbase ,without using hoping to get a reply soon...

Anonymous said...

i want to know how to scroll news headlines in ovrewebsite

Narmi Raja said...

Hi good job ........

i need one help how upload image postgres sql database using ....

Jaime Ballesteros Saravia said...

Gracias, tu ejemplo es muy claro y sencillo, justo lo que uno busca, me ayudo mucho.
Now, I'm working with telerik ajax controls if you know, please, i need help. thanks

Anonymous said...

thanks very well, thank you. really appreciate it.

Anonymous said...

Very useful. I needed to serve invoices to my customers in pdf and xlm files and thanks to your sharing I am done! Regards!

Anonymous said...

string filePath = dgvfiledown.DataKeys[gvrow.RowIndex].Value.ToString();

i got an error in this line .
"Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"

Anonymous said...

Please help me to the post 31 ...

Hemraj Janwa said...

My best website..its very useful for new learner. Thanks a lot to Developer.

Kalim.Paracha said...

hi suresh....
i have some problem to use this code
if you some kind of information how to use this code in layered architecture. you know layered work very different..plz tell us some idea ....

Anonymous said...

hanks very well, thank you. really appreciate it.

Anonymous said...

we use this code than files not save in file folder in project and saved to datbase correctley plz help me

Anonymous said...

Hi sir,

I need help from your side.

If I am upload my resume means to specific fields to fetch the textbox control. for eg: email, firstname, lastname, role, mobile no to get values for to upload the resume to automatically to bind the text box control.

I need coding path and examples
please help me sir

Ashok Sahu said...

great brother your coding always help me..thanks a lot....

Anonymous said...

Hello sir give me some application of wcf

Anonymous said...

Thanks a lot .......this article was very helpful

Anonymous said...

thank u very much

Anonymous said...

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
i'm getting error like this..please help me

Water said...

Sir, I have error in downloading the file after uploading. Pls help me with this.

swornalatha said...

Sir,i want to scan the virus when uploading the files .. pls tell c# code..pls help me sir..

Anonymous said...

if i dont want to use grid view then can i download multiple files?

Johann said...

Hi. Great post. Works a charm.
I was however wondering if it is possible to save files to e.g. Dropbox or Azure cloud or Amazon or any other hosting using your steps? Or how about FTP?
How would you incorporate a username and password?

manikandan a said...

how to download sever side file through the gridview in

fungus said...

Server.MapPath is used to translate a virtual path (web path).
I want to upload file in different drive example D:/UploadFolder/ its physical path.
is there any way to upload and download file from physical path not from virtual path

Gayathri N said...

Thank you very nice article

chetan patel said...

what should be the value of date,size & type in parameters ??

chetan patel said...

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
i'm getting error like this..please help me

Darshan Kshirasagar said...

Amazing code thnx for this....:)

Anonymous said...

Hi, very nice code, I have an issue with gvDetails and FileUpload1 ..
error /// The name 'gvDetails' does not exist in the current context any help

syed irfan said...

Thanks dude...ITS WRORKING

sairam pamidi said...

How To Load File Automatically into File Up loader.

I have requirement , I have asp page with file up-loader and button name "upload"...with out using the browse ,i want load some default file in file up-loader ,suppose , I have folder in c:\serverfloder and i have image "image1.jpg" in that ..when user request 1 time ,i want to automatically load the file into file up-loader ..based user requirement we give chance the change the file file ....i don't want to restrict the user.

Dillip Kumar said...

Suresh sir ...Please help me ..... my question is how to view a uploaded document without downloading that doc...... just i need to view that doc in page itself

Farooq said...

do we have same thing for java ?

Darshan Kshirasagar said...

How to delete the uploaded document sir plz help me.

Ramanji Singh said...

how to count length of character in custom editor using

Ramanji Singh said...

plz solve my problem sir..

Anonymous said...

All Nice aritcal is very useful to me ..Thanks..

Rama krishna said...

good article

Anonymous said...

sir ji i have one problem when i use download code getting some unable to valid expression

Anonymous said...

hi,once i submit m resume ,it need to be saved in a folder with the name of the user along with time.can u help me in this regard

shivangi said...

Hi suresh sir !
I'm shivangi. Your articles are really good n helpful. These articles helped me a lot in my project .

Anonymous said...

How to delete a file which has upload from datagrid? Please help

Bhaskar Reddy said...

Good Post


Bhagyashree Muthiyan said...

I create word doc to save with proper naming?

kapil bhati said...

I want to do same Thing in Windows application how can i do pls reply....


조남선 said...

My twitter account did not registered api twitter .com/oauth/request_token. Can i update my account.
But i don't know my callback url.

Anonymous said...

Very helpful article. Only I have a problem. I used your code and my page shows all images, looks good! But except imagges it shows Thumb.db link. When I click on the link - there is nothing. There is no such db in the directory. How can I get rid of showing this link?
Please, advise.

Jumbowallpapers said...

this code is not work in internet explorer

Anonymous said...

hi..which tool u have used for live demo..

Raman Deep said...

thankyou so much.........

Anonymous said...

very nice app........
thank you

Anonymous said...

code is running without any error, but not getting the download option,can any one help me pz

Anonymous said...

Hi Suresh ,

Everything is Working Fine , But i want to download file directly to "D:\\Project" without asking Open save dialogue .

Prasad Venkata said...

Hi Suresh,
This is working fine with fileupload control and save file in a desired location. I am asking one thing, that i need to save file that came from my database in a desired location as above. can you please suggest me without fileupload control.

banesh said...

Good website for fresher as well as experienced..!! Keep updating Bro!!

Anonymous said...

Could not complete the operation due to error c00ce514.

romosabdorachim said...

Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)

Why "GridViewRow" and Response.TransmitFile undifined in 2003 / visual studio 2003...???

Anonymous said...

Hi Suresh,

I am using below code for download.

String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");

Upon click of the download button, i am getting Open/Save/Cancel dialog box, but i still able to click download button once again, without answering the dialog box. I wanted to open Model Dialog box. Please guide me in this.


Anonymous said...

Hi Suresh,
My scenerio is little bit different, I want to save and download the website in html format with running it on browser just like searched a lots but dint get any solution.Kindly tell me if you have any answer.


Uttam said...

If its inside the Update Panel then ?

Anonymous said...

Hi suresh,
Article is very nice.
But one error is display...String or binary data would be truncated.
The statement has been terminated.

Anonymous said...

You are my god

Anonymous said...

dear sir in behind code c# with it 's ok but in when I try upload it show me object reference not
instance an object could you show me?

Dhiren Talati said...

Can u teach file upload and download from remote server using FTP?

VtBear said...

How can you delete the file and the line of the gridview at the same time

Rajesh said...


Anonymous said...

Thank U So Much..... It is Very Much Useful For Me....!

Shrikesh kale said...

Can we hide the (download) save pop up . and gives physical path like ("E:\ABC") folder name ?

If know please tell me . thanks in advance.

Give your Valuable Comments

Other Related Posts

© 2015 All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.