Aspdotnet-Suresh

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

save/upload files in folder and download files from folder in asp.net

Feb 27, 2012
Introduction:

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 asp.net.


Description:
  
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 asp.net.
To implement this first design table in your database like below to save file details in database.
Column Name
Data Type
Allow Nulls
Id
int(set identity property=true)
No
FileName
varchar(50)
Yes
FilePath
varchar(50)
Yes

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="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Save and Download Files from file system</title>
<style type="text/css">
.modalBackground
{
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 }

</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileUpload1" runat="server" /><br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" onclick="btnUpload_Click" />
</div>
<div>
<asp:GridView ID="gvDetails" CssClass="Gridview" runat="server" AutoGenerateColumns="false" DataKeyNames="FilePath">
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FileName" HeaderText="FileName" />
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="lnkDownload_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
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)
{
if(!IsPostBack)
{
BindGridviewData();
}
}
// Bind Gridview Data
private void BindGridviewData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from FilesTable",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
// Save files to Folder and files path in database
protected void btnUpload_Click(object sender, EventArgs e)
{
string filename = Path.GetFileName(fileUpload1.PostedFile.FileName);
fileUpload1.SaveAs(Server.MapPath("Files/"+filename));
con.Open();
SqlCommand cmd = new SqlCommand("insert into FilesTable(FileName,FilePath) values(@Name,@Path)",con);
cmd.Parameters.AddWithValue("@Name",filename );
cmd.Parameters.AddWithValue("@Path", "Files/"+filename );
cmd.ExecuteNonQuery();
con.Close();
BindGridviewData();
}
// 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 + "\"");
Response.TransmitFile(Server.MapPath(filePath));
Response.End();
}
VB.NET Code

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
BindGridviewData()
End If
End Sub

' Bind Gridview Data
Private Sub BindGridviewData()
con.Open()
Dim cmd As New SqlCommand("select * from FilesTable", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
con.Close()
gvDetails.DataSource = ds
gvDetails.DataBind()
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))
con.Open()
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)
cmd.ExecuteNonQuery()
con.Close()
BindGridviewData()
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 & """")
Response.TransmitFile(Server.MapPath(filePath))
Response.[End]()
End Sub
End Class


Demo

Download sample code attached

 

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

Get the latest Asp.net, C#.net, 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

98 comments :

Anonymous said...

Nice aritcal .......it 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 good.......it'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

Bhaskara said...

good post .

Thanks ,
bhaskar
http://csharpektroncmssql.blogpsot.com

suresh gupta said...

very nice article specially those who are beginner.

Anonymous said...

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

Anonymous said...

sdfdf

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...

@muthu...
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...

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

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.

Admin said...

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

Anonymous said...

i faced exception in linkbtn coding .

Suresh Dasari said...

@Cherry...
To solve that error you need to increase the upload size of your files in web.config check this article
http://www.aspdotnet-suresh.com/2010/12/how-to-restrict-size-of-upload-file-in.html

Unknown 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 gridview....am hoping to get a reply soon...

Anonymous said...

i want to know how to scroll news headlines in ovrewebsite

Unknown said...

Hi good job ........

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

Unknown said...

Gracias, tu ejemplo es muy claro y sencillo, justo lo que uno busca, me ayudo mucho.
Now, I'm working with telerik asp.net 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 ...

Unknown said...

My best visit.....best website..its very useful for new programmer...as 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

Unknown 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?

Unknown said...

how to download sever side file through the gridview in asp.net

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

Unknown said...

Thank you very nice article

Unknown said...

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

Unknown 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

Dek Ganesh 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

Unknown said...

Thanks dude...ITS WRORKING

à°¸ాà°¯ిà°°ాం 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.

Unknown 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 ?

Dek Ganesh said...

How to delete the uploaded document sir plz help me.

Unknown said...

how to count length of character in custom editor using asp.net

Unknown said...

plz solve my problem sir..

Anonymous said...

All Nice aritcal .......it 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
c#

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

Unknown said...

Good Post

Thanks
Bhaskar.

Unknown said...

I create word doc dynamicaly.how to save with proper naming?

Unknown said...

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

Thanks

Unknown 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..

Unknown 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 .

Unknown 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.

Anonymous said...

Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Response.TransmitFile(Server.MapPath(filePath))

Why "GridViewRow" and Response.TransmitFile undifined in asp.net 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.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();

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.

Thanks
Priya.

Anonymous said...

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

Regards

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 asp.net it 's ok but in vb.net when I try upload it show me object reference not
instance an object could you show me?

Anonymous 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...

good

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.

Anonymous said...

thank you very much for this tutorial.

Unknown said...

thanks very short n valuable code

Unknown said...

hi this is jyoti.
i don't want to use fileupload control . i retrive value from the database in gridview then i want to to download

Pk said...

Can we upload video and audio and download??

ashwini said...

thank u.can i know how to retriew file stored in database with varbinary.

Unknown said...

I need this in windows form application where i browse a file and save in the folder only name of file i do save in database table.
I already upload the file and displayed in gridview now i want to download the files from grid view

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

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