In this tutorial, you'll learn how to delete files from a server folder using ASP.NET (C# and VB.NET) and the JavaScript Fetch API. The example demonstrates how to send an asynchronous request to the server, delete the selected file, and update the user interface without refreshing the page, resulting in a cleaner and more responsive user experience.
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>Fetch files from a folder and 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; } } } } }
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")
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 ClassIf 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.
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)); } }
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
JavaScript Fetch API
<script>
document.addEventListener("DOMContentLoaded", function () {
const div = document.createElement("div");
let cnt = 1;
document.querySelectorAll("p a").forEach(link => {
link.addEventListener("click", function (event) {
if (confirm("Are you sure?")) {
event.preventDefault();
const para = this.parentElement;
const fileName = para.textContent.replace(this.textContent, "").trim();
fetch("frmDel.aspx?FileName=" + encodeURIComponent(fileName), {
method: "POST"
})
.then(response => {
if (!response.ok) {
throw new Error("Failed to delete file.");
}
// Hide and remove the paragraph.
para.style.transition = "all 0.7s ease";
para.style.opacity = "0";
setTimeout(() => {
para.remove();
}, 700);
// Show confirmation.
div.innerHTML = `${cnt} file${cnt > 1 ? 's' : ''} deleted`;
div.style.float = "right";
document.getElementById("container").appendChild(div);
cnt++;
})
.catch(error => {
console.error(error);
alert("An error occurred while deleting the file.");
});
}
});
});
});
</script>What Does This Script Do?
This script lets users delete files from a server folder without refreshing the page. When a user clicks a Delete link, it sends a Fetch API request to an ASP.NET page, which deletes the selected file. After a successful deletion, the file entry fades out and is removed from the page, while a counter displays the number of files deleted.
Why Use Fetch API Instead of jQuery AJAX?
The Fetch API is a modern, built-in JavaScript feature for making HTTP requests. Unlike jQuery AJAX, it does not require the jQuery library, resulting in smaller page sizes and cleaner code. It also works seamlessly with modern JavaScript features such as Promises and async/await, making it the preferred choice for new web applications.
You may also like: How to Fetch and Display Paginated Data in an HTML Table Using Web API with Async/Await
