Introduction
This article explains how to delete a file, of files listed in a DropDownList, existing in a folder.
Add the following namespaces in the .cs file:
- using System;
- using System.Drawing;
- using System.IO;
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>how to delete a file from a folder in ASP.Net using C#</title>
- <style type="text/css">
- .auto-style1 {
- width: 88px;
- }
- </style>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <table>
- <tr>
- <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>
- <asp:ListItem>file1.txt</asp:ListItem>
- <asp:ListItem>file2.pdf</asp:ListItem>
- <asp:ListItem>file3.doc</asp:ListItem>
- <asp:ListItem></asp:ListItem>
- </asp:DropDownList>
- </td>
- </tr>
- <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>
- </table>
- </div>
- </form>
- </body>
- </html>
When the dropdown has all file names you can select any file to be deleted and click on the button "Delete". It will check if the file exists; if it exists then it will delete file else show you a message in the lbl_output that your file does not exist.
Write the following 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
- {
- file.Delete();
- lbl_output.Text = file_name + " file deleted successfully";
- lbl_output.ForeColor = Color.Green;
- }
- else
- {
- lbl_output.Text = file_name + " This file does not exists ";
- lbl_output.ForeColor = Color.Red;
- }
- }

Abul Bashar SardarPosted May 28, 2024, 10:03 AM
This is fantastic, working nicely. Thanks for your effort.
Palanikumar DPosted Dec 29, 2023, 5:41 AM
Good Example Neha
Dharmendra Kumar PanditPosted Jun 12, 2018, 4:28 AM
Thanks its working fine.
shabin lalPosted Mar 31, 2018, 5:23 AM
Ya its working thank you for the kind information
Vaibhav KumarPosted Jun 9, 2017, 4:38 AM
If file is already in use then this code will fail.
Upendra Pratap ShahiPosted Sep 8, 2015, 5:35 AM
good one
Soumya Ranjan MaharanaPosted May 8, 2015, 3:35 AM
File not deleted if it is being used by another process (if its view somewhere like jpg files.)
Aman JainPosted Aug 1, 2014, 2:21 AM
thanks it worked...