ASP.Net : Delete files from folder | Neha Sharma


This article explains how to delete a file consisting in your folder. Requirement:
Add below namespaces in .cs file:

using System;
using System.Drawing;
using System.IO;

code.aspx :

I have files in my application folder named “files”. i want to delete some file from  those so first i bind all file name  in to a dropdown list. Write below code in the .aspx page.

<html xmlns="">
<head id="Head1" runat="server">
<title>how to delete a file from a folder in using c#</title>
    <style type="text/css">
        .auto-style1 {
            width: 88px;
<form id="form1" runat="server">
<td>Select file to delete</td>
<td class="auto-style1">
    <asp:DropDownList ID="DropDownList1" runat="server" Height="16px" Width="88px">
        <asp:ListItem>Select file</asp:ListItem>
<tr><td></td><td class="auto-style1"><asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" /> </td></tr>
<tr><td colspan="2"><asp:Label ID="lbl_output" runat="server"/></td></tr>

Code.cs :

When dropdown have all file names now you can select any file which you want to delete and click on button “Delete” it ll check if your file is existing or not if exist it ll delete file else show you a message that your file is     not existing in the lbl_output.
Write below code on the button delete:

protected void btnDelete_Click(object sender, EventArgs e)
        string file_name = DropDownList1.SelectedItem.Text;
        string path = Server.MapPath("files//" + file_name);
        FileInfo file = new FileInfo(path);
        if (file.Exists)//check file exsit or not
            lbl_output.Text = file_name + " file deleted successfully";
            lbl_output.ForeColor = Color.Green;
            lbl_output.Text = file_name + " This file does not exists ";
            lbl_output.ForeColor = Color.Red;

Save all and view the page in browser it ll work fine.