Asp.net delete file file on Server C#.net and VB.net code

Asp.net delete file file on Server C#.net and VB.net code

In this post I will show you how to delete particular file on server or file uploaded at upload folder. Demo has both C#.net and VB.net code.

Aspx page

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Asp.net File Upload and Delete</title>
</head>
<body>
    <form id="form1" runat="server">
        <div> 
        <asp:TextBox ID="txtFileName" runat="server"></asp:TextBox> 
        <asp:Button ID="Button2" runat="server" Text="Delete" OnClick="Button2_Click" />
    </form>
</body>
</html>

Asp.net C# code behind to delete file on Server

using System;
using System.Web;
using System.IO;
public partial class FileUploadDemo : System.Web.UI.Page
{  
  protected void Button2_Click(object sender, EventArgs e)
  {
    string filePath = Server.MapPath("uploads");
    filePath = filePath + @"\" + txtFileName.Text;
    if(File.Exists(filePath))
    {
      File.Delete(filePath);
    }
    
  }
}

Note: First we check for the existence of the file on server. This will avoid file not found exception to occur.

Asp.net with VB.net code Delete file on Server

 

Imports System.Web Imports System.IO Public Partial Class FileUploadDemo Inherits System.Web.UI.Page Protected Sub Button2_Click(sender As Object, e As EventArgs) Dim filePath As String = Server.MapPath("uploads") filePath = (filePath & "\") + txtFileName.Text If File.Exists(filePath) Then File.Delete(filePath) End If End Sub End Class

Description

We are asking users to input the name of the file on server to delete. I have some files inside upload folder that folder you too need to create if you are running above example. The name of folder is upload .

You can also see how to upload file on server

Sql Server MirroringASP.net File HandlingC# Delete All Files In DirectoryAsp.net File UploadRead Text File in (C#.net or VB.net)ASP net Write Text On Image C#.net and Vb.net programASP.net monitor server Visual Studio Recover Deleted FileAsp.net Create Folder On ServerAsp.net Interview Questions for 2 years or 3 years experianceC#- how to download file (Vb.net)

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.