Delete Files from a Folder Inside a Application after Uploaded in ASP.Net

Follow the below code or download the zipped code.

Here I am writing program to upload files into a folder and after it how to delete these files one by one.

.aspx code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:FileUpload ID="FileUpload1" runat="server" />

        &nbsp;&nbsp;

        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="upload" />

        &nbsp;&nbsp;&nbsp;

        <br />

        <br />

        <br />

        <br />

        <asp:DropDownList ID="DropDownList1" runat="server">

        </asp:DropDownList>

        &nbsp;

        <asp:Button ID="Button2" runat="server" Text="delete" OnClick="Button2_Click" />

        <br />

    </div>

    </form>

</body>

</html>

.cs code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO;

public partial class Default2 : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!Page.IsPostBack)

        {

            bind();

        }

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        string silename = FileUpload1.FileName;

        string path = Server.MapPath("~/upload/");

        string fullpath = path + silename;

        FileUpload1.SaveAs(fullpath);

        bind();

    }

    public void bind()

    {

        DropDownList1.Items.Clear();

        string path = Server.MapPath("~/upload/");

        Directory.GetFiles(path);

        foreach (var filenam in Directory.GetFiles(path))

        {

            string filename = filenam.ToString();

            filename = filename.Replace(path, "").ToString();

            DropDownList1.Items.Add(filename.ToString());

        }

        DropDownList1.DataBind();

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        string file = DropDownList1.SelectedItem.ToString();

        string path = Server.MapPath("~/upload/");

        string fullpath = path + file;

        File.Delete(fullpath);

        bind();

    }

}

Ebook Download
View all
Learn
View all