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

← PrevNext →

We can delete files stored in a remote server using Asp.Net C# and Vb.Net with a little help from jQuery Ajax methods. The files in this context can be anything like Images, PDF’s, Text files etc. Asp.Net File class in System.IO namespace provides the necessary methods to accomplish this task with ease.

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

The example we are showing has two forms. The first one fetches files from a remote folder and displays the list of files on the web page. We are not specifying particular type of files in our example, but file types can be specified using file extensions, like *.pdf, *.jpg, *.gif etc.

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

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

Also Read: How to delete old Files in a Folder or delete files older than one day using C#

CSS
<head>
    <title>Delete Files in a Folder using jQuery Ajax and Asp.Net</title>

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

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

The Markup
<body>
    <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>
The Script
<script>
    $(document).ready(function() {

        var div = document.createElement('div');
        var cnt = 1;

        // LINK (<a>) CLICK INSIDE THE PARAGRAPH (<p>).

        $('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 as the main container and the file container. The HTML Paragraphs “<p></p>” and links “<a></a>” inside the containers, are created dynamically from code behind. The Click event of the links (“<a></a>”) will invoke the jQuery Ajax method instead of redirecting or opening another page.

We are 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, '')

Fetch files from a Folder to display (C#)
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;
                }
            }
        }
    }
}
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
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

(Tested on Chrome, Safari, IE and Firefox)

Related Post: How to Create or Remove Folders and Subfolders in Asp.Net C# and Vb.Net

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 range from User Authentication, Password Protection, Database Triggers and Folder permissions. Also, 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 →