How to Delete Files from a Folder Using jQuery AJAX and ASP.NET (C# & VB.NET)

← PrevNext →

Last updated: 16th June 2026

You can delete files stored in a remote server in ASP.NET using jQuery Ajax. The files can be anything like images, PDF's, text files etc. ASP.NET FileInfo class of System.IO namespace provides the necessary methods to accomplish this task with ease.
See this demo

👉 jQuery AJAX is no longer the default choice in modern web development. Many developers use the JavaScript Fetch API instead. Therefore I would recommend checking this article, which uses Fetch API to delete files in a folder.

Why Use Fetch API Instead of jQuery AJAX?

What this example does?

The example here has two forms (web pages). The first one fetches files from a remote folder and displays the file list on the web page. I have not specified any particular type of files in this example. However, file types can be specified using file extensions, like *.pdf, *.jpg, *.gif etc. See this code here.

These files will be deleted by calling another form frmDel.aspx, which has a procedure to delete the selected file, one at a time. This form will be called from the main (or master) form using Ajax. The name of the "file" will be passed as a QueryString parameter.

But first, lets see the Markup.

The CSS and Markup

In the markup section, I just have a DIV element which will serve as a container, which will show a list of files extracted from a folder dynamically using code behind procedure.

<head>
    <style>
        div p {
            padding:5px; 
            border:solid 1px #CCC; 
            margin:2px auto;
        }

        div p a {
            font-weight:bold; 
            float:right; 
            text-decoration:none; 
            color:red;
        }
    </style>
</head>
<body>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="scriptManager" runat="server" EnablePageMethods="true" />

        <div style="width:700px" id="container">
            <div id="fileContainer" runat="server"></div>
        </div>
    </form>
</body>

C# code to fetch files from a folder and display

using System;
using System.IO;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            DirectoryInfo Fold = new DirectoryInfo(Server.MapPath("files"));
            FileInfo[] objFI = Fold.GetFiles("*.*");    // GET FILE INFO INSIDE THE FOLDER.

            int iCnt = 0;
            if (objFI.Length > 0)
            {
                foreach (FileInfo file in objFI)
                {
                    System.Web.UI.HtmlControls.HtmlGenericControl P = 
                        new System.Web.UI.HtmlControls.HtmlGenericControl("P");
                        
                    P.InnerHtml = objFI[iCnt].Name + "<a href='' id='del" + iCnt + "'>X</a>";

                    fileContainer.Controls.Add(P);  // EMBED PARAGRAPH IN THE CONTAINER.
                    iCnt += 1;
                }
            }
        }
    }
}

The above code extracts all files from the "files" folder. However, specific file types can be looked and extracted using file extensions, like *.pdf, *.jpg, *.gif etc. For example,

Dim listfiles As FileInfo() = root.GetFiles("*.pdf")

VB.NET
Option Explicit On
Imports System.IO

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) 
            Handles form1.Load
        If Not Page.IsPostBack Then
            Dim root As New DirectoryInfo(Server.MapPath("files"))
            Dim objFI As FileInfo() = root.GetFiles("*.*")  ' GET FILE INFO INSIDE THE FOLDER.

            Dim iCnt As Integer = 0
            
            If objFI.Length > 0 Then
                For Each file As FileInfo In objFI
                    Dim P As New HtmlGenericControl("P")
                    P.InnerHtml = objFI(iCnt).Name & "<a href='' id='del" & iCnt & "'>X</a>"

                    fileContainer.Controls.Add(P)   ' EMBED PARAGRAPH IN THE CONTAINER.
                    iCnt += 1
                Next
            End If
        End If
    End Sub
End Class

If you are done with file extraction procedure. Run the application to check if you are able to fetch files from the "files" folder.

👉 Now lets write code behind procedure to delete the files.

The File Deletion Procedure (C#)
using System;
using System.IO;
using System.Web.UI;

public partial class frmDel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string sFileName = Request.QueryString["FileName"];
        if (sFileName != "") 
        {
            DeleteFiles(sFileName); // CALL DELETE PROCEDURE.
        }
    }

    protected void DeleteFiles(string sFileName)
    {
        // DELETE FILES USING THE "FILE" CLASS.
        File.Delete(Server.MapPath("files/" + sFileName)); 
    }
}
VB.NET
Option Explicit On
Imports System.IO

Partial Class frmDel
    Inherits System.Web.UI.Page

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs)   
            Handles form1.Load
        If Request.QueryString("FileName") <> "" Then
            DeleteFiles(Request.QueryString("FileName"))    // CALL DELETE PROCEDURE.
        End If
    End Sub

    Private Sub DeleteFiles(ByVal sFileName As String)
        // DELETE FILES USING THE "FILE" CLASS.
        File.Delete(Server.MapPath("files/" & sFileName)) 
    End Sub
End Class

Finally, the jQuery script to delete files in the folder

<script>
    $(document).ready(function() {
        var div = document.createElement('div');
        var cnt = 1;

        // Link (<a>) click event inside the P element.
        $('P a').click(function(event) {
            if (confirm("Are you sure?")) {

                event.preventDefault();    // PREVENT DEFAULT ACTION OF THE LINK BUTTON.

                var para = $(this).parent();

                $.ajax({
                    type: "POST",
                    url: "frmDel.aspx?FileName=" + para.text().replace(this.innerHTML, ''),
                    complete: function() {
                        para.slideUp(700, function() { 
                            para.remove(); 
                        });  // FILE DELETED, HIDE THE PARAGRAPH.
    
                        // CONFIRM, THE FILE IS DELETED.
                        div.innerHTML = cnt + ' files deleted';
                        div.setAttribute('style', 'float:right');
                        $('#container').append(div);
                        cnt = cnt + 1;
                    }
                });
            }
        });
    });
</script>

In the above script, we have two "DIV" elements. 1, that serves as the parent container and 2, the file list container. The HTML Paragraphs <p></p> and links <a></a> inside the containers, are created dynamically using code behind procedure in the 1st form.

The Click event of the "links" (<a></a>) will invoke the jQuery AJAX method instead of redirecting or opening another page.

Also using event.preventDefault() to prevent the link’s click event to perform any redirection, and instead allow Ajax to handle the call.

url:"frmDel.aspx?FileName=" + para.text().replace(this.innerHTML, '')

Conclusion

While deleting files in a folder or deleting records in a database, do write necessary security procedures, both at the client and server side. These procedures can be like "user authentication", password protection, database Triggers and Folder permissions.

In-addition, protect your data using potent FireWall softwares. In the above example, we are using the Confirm prompt, and it is effective. Make sure no one performs these task with out you consent or permission.

See this demo

← PreviousNext →