How To Upload And Download Files Using Asp Net And C# Part 139
Link for code samples used in the demo
Link for csharp, asp.net, ado.net, dotnet basics, mvc and sql server video tutorial playlists
In this video, we will discuss
1. Uploading files
2. Displaying the list of files that are already uploaded
3. Downloading files
When the files are uploaded, they should be uploaded to a folder on the web server. In our case, we will be uploading to “Data” folder.
WebForm1.aspx code:
[asp:Button ID=”Button1″ runat=”server” Text=”Upload”
OnClick=”Button1_Click” /]
[asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
OnRowCommand=”GridView1_RowCommand” BackColor=”White”
BorderColor=”#CC9966″ BorderStyle=”None”
BorderWidth=”1px” CellPadding=”4″]
[asp:LinkButton ID=”LinkButton1″ runat=”server”
CausesValidation=”False”
CommandArgument=”
CommandName=”Download” Text=’
[HeaderStyle BackColor=”#990000″ Font-Bold=”True”
ForeColor=”#FFFFCC” /]
[PagerStyle BackColor=”#FFFFCC” ForeColor=”#330099″
HorizontalAlign=”Center” /]
[SelectedRowStyle BackColor=”#FFCC66″ Font-Bold=”True”
ForeColor=”#663399″ /]
WebForm1.aspx.cs code:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;
FileUpload1.PostedFile
.SaveAs(Server.MapPath(“~/Data/”) + fileName);
}
DataTable dt = new DataTable();
dt.Columns.Add(“File”);
dt.Columns.Add(“Size”);
dt.Columns.Add(“Type”);
foreach (string strfile in Directory.GetFiles(Server.MapPath(“~/Data”)))
{
FileInfo fi = new FileInfo(strfile);
dt.Rows.Add(fi.Name, fi.Length.ToString(),
GetFileTypeByExtension(fi.Extension));
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
private string GetFileTypeByExtension(string fileExtension)
{
switch (fileExtension.ToLower())
{
case “.docx”:
case “.doc”:
return “Microsoft Word Document”;
case “.xlsx”:
case “.xls”:
return “Microsoft Excel Document”;
case “.txt”:
return “Text Document”;
case “.jpg”:
case “.png”:
return “Image”;
default:
return “Unknown”;
}
}
protected void GridView1_RowCommand(object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == “Download”)
{
Response.Clear();
Response.ContentType = “application/octect-stream”;
Response.AppendHeader(“content-disposition”, “filename=”
+ e.CommandArgument);
Response.TransmitFile(Server.MapPath(“~/Data/”)
+ e.CommandArgument);
Response.End();
}
}
Please make sure to include the following using declarations in the code behind file.
using System.IO;
using System.Data;
Make sure to replace with GREATERTHAN symbol.