Delete Files in a Folder using jQuery Ajax and Asp.Net - C# and Vb.Net

← PrevNext →

Last updated: 10th April 2024

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.

Two articles that you must go through to understand more about System.IO namespace in Asp.Net.

1) How to get file size in Asp.Net in C# and VB.
2) How to get filename and file extension from a URL using System.IO properties in Asp.Net

Many times we came across queries like, is it possible to delete files using JavaScript or jQuery. Scripts written at the client side cannot directly manipulate files or data situated at the server. However, jQuery Ajax methods can call functions at the server to do the necessary task for us. Ajax can do this efficiently, by adding a little animation and color.

See this demo

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, particular 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 let 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 →