Delete Files From Folder in ASP.NET

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;

I have files in my application folder; the folder is named "files". I want to delete some file from those so first I list all the file names in a dropdown list. Write the following code in the .aspx page:

<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>

Code.cs

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;
      }
}

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

Up Next
    Ebook Download
    View all
    Learn
    View all