How to upload and download files using asp net and c# Part 139

42
2



Text version of the video

Slides

All ASP .NET Text Articles

All ASP .NET Slides

ASP.NET Playlist

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic

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:
[div style=”font-family:Arial”]
[asp:FileUpload ID=”FileUpload1″ runat=”server” /]
[asp:Button ID=”Button1″ runat=”server” Text=”Upload”
OnClick=”Button1_Click” /]
[br /]
[br /]
[asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
OnRowCommand=”GridView1_RowCommand” BackColor=”White”
BorderColor=”#CC9966″ BorderStyle=”None”
BorderWidth=”1px” CellPadding=”4″]
[Columns]
[asp:TemplateField HeaderText=”File” ShowHeader=”False”]
[ItemTemplate]
[asp:LinkButton ID=”LinkButton1″ runat=”server”
CausesValidation=”False”
CommandArgument='[%# Eval(“File”) %]’
CommandName=”Download” Text='[%# Eval(“File”) %]’]
[/asp:LinkButton]
[/ItemTemplate]
[/asp:TemplateField]
[asp:BoundField DataField=”Size” HeaderText=”Size in Bytes” /]
[asp:BoundField DataField=”Type” HeaderText=”File Type” /]
[/Columns]
[FooterStyle BackColor=”#FFFFCC” ForeColor=”#330099″ /]
[HeaderStyle BackColor=”#990000″ Font-Bold=”True”
ForeColor=”#FFFFCC” /]
[PagerStyle BackColor=”#FFFFCC” ForeColor=”#330099″
HorizontalAlign=”Center” /]
[RowStyle BackColor=”White” ForeColor=”#330099″ /]
[SelectedRowStyle BackColor=”#FFCC66″ Font-Bold=”True”
ForeColor=”#663399″ /]
[SortedAscendingCellStyle BackColor=”#FEFCEB” /]
[SortedAscendingHeaderStyle BackColor=”#AF0101″ /]
[SortedDescendingCellStyle BackColor=”#F6F0C0″ /]
[SortedDescendingHeaderStyle BackColor=”#7E0000″ /]
[/asp:GridView]
[/div]

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 LESSTHAN and ] with GREATERTHAN symbol.

Nguồn:https://wijstaanvooronzegrondrechten.org/

Xem Thêm Bài Viết Khác:https://wijstaanvooronzegrondrechten.org/cong-nghe

42 COMMENTS

  1. hi , im getting the following err
    System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:myfoldersqlscript.txt'.'

    at FileUpload1.PostedFile

    .SaveAs(@"C:myfolder" + fileName);

    even i tried as shown in your video..

  2. Hi sir nice video…..how to write into the textfile after publishing the pgm into the server….we are only able to write on the textfile locally to the desktop but failing write once we have published…we have given permission to the folder but receiving permission denied error when tried it from server…..Thank you in advance….

    string physicalPath = (@"D:FlashdataLabeltext.txt");

    File.WriteAllText(physicalPath, String.Empty);

    FileStream stream = new FileStream(physicalPath, FileMode.Open, FileAccess.ReadWrite);

    StreamWriter writer = new StreamWriter(stream);

    SqlConnection con6 = new SqlConnection(constr6);

    con6.ConnectionString = constr6;

    SqlCommand com = new SqlCommand(" select PMax,VOC,ISC,VPM,IPM,PSV,AssignMSN,MSN_Mat,PSN from [LabelMSN]where PSN='" + txtpsn.Text + "' order by id desc", con6);

    con6.Open();

    SqlDataReader reader = com.ExecuteReader();

    while (reader.Read())

    {

    writer.Write(reader["PMax"].ToString());

    writer.Write(",");

    writer.Write(reader["VOC"].ToString());

    writer.Write(",");

    writer.Write(reader["ISC"].ToString());

    writer.Write(",");

    writer.Write(reader["VPM"].ToString());

    writer.Write(",");

    writer.Write(reader["IPM"].ToString());

    writer.Write(",");

    writer.Write(reader["PSV"].ToString());

    writer.Write(",");

    writer.Write(reader["AssignMSN"].ToString());

    writer.Write(",");

    writer.Write(reader["MSN_Mat"].ToString());

    writer.Write(",");

    writer.Write(reader["PSN"].ToString());

    //writer.WriteLine();

    }

    reader.Close();

    writer.Close();

    stream.Close();

    con6.Close();

    }

  3. Hello Venkat i have been a regular viewer of your channel, learnt many things here appreciate your work its commendable kudos.. here i am in need can you upload a video on change default download path chrome using c# if possible asap ?????

  4. sir i implement your code in our project for download file but its give me exception plzzzz tell me how to resolve System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:UsersFaizisourcereposLab_Automation_SystemLab_Automation_SystemFiles'.'????????//

  5. sir,is it possible do all operations (inser,delete,update,upload and download) in one gridview if it is possible please send code to my email …

  6. Thank you,,, and I have a doubt.. is any possible to upload text ( like feedback or comment or like WhatsApp chats )only not as document?

  7. Thank You so much sir… Everything is working fine but when i am trying to upload a "mp3" file then it's not working and error message showing "This site can’t be reached". please help

  8. hi your videos are awesome, i have been watching these videos from almost a year. Sir, you are doing a great job. Now to the point, how to preview the pictures before uploading them

  9. Hello Kudvenkat, how to make the download work with update panel? I am getting the error: JavaScript runtime error: Unable to get property 'PRM_ParserErrorDetails' of undefined or null reference

LEAVE A REPLY

Please enter your comment!
Please enter your name here