V24s

"Get Updates : Subscribe to our e-mail newsletter to receive updates........" "Good Luck frnds" Admission 2018 Application Form 2018 Colleges Entrance Exam 2018 Results 2018 Notification 2018 University Educational Jobs 2018 Government Jobs 2018

Search This Blog v24s guys

Follow by Email

04 April, 2013

Delete a File from Asp.net Uploaded Folder using C#, VB.NET

Introduction

Here I will explain how to delete a file from a folder in 
asp.net using c# and vb.net.

Description: 
   
In previous articles I explained 
Difference between sessionstate and viewstate, Highlight gridview rows on mouseover in jQuery, and many articles relating to asp.net, c#,vb.net and JQuery. Now I will explain how to delete a file from a folder in asp.net using c# and vb.net.

To implement this functionality we need to write the following code like as shown below


string FileName ="test.txt";
string Path = "E:\\" + FileName;
FileInfo file = new FileInfo(Path);
if (file.Exists)
{
file.Delete();
}
If you want to see it in complete example check below code


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>how to delete a file from a folder in asp.net using c#</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td><b>Enter File Name to Delete:</b></td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
</tr>
<tr><td></td><td><asp:Button ID="btnDelete" runat="server" Text="Delete File" /> </td></tr>
<tr><td colspan="2"><asp:Label ID="lblResult" runat="server"/></td></tr>
</table>
</div>
</form>
</body>
</html>
Now open code behind file and add following namespaces

C# Code


using System;
using System.Drawing;
using System.IO;
After that write the following code in code behind


protected void btnDelete_Click(object sender, EventArgs e)
{
string filename =txtName.Text;
string path = "E:\\" + filename;
FileInfo file = new FileInfo(path);
if (file.Exists)
{
file.Delete();
lblResult.Text = filename + " file deleted successfully";
lblResult.ForeColor = Color.Green;
}
else
{
lblResult.Text = filename + " file not exists in filepath";
lblResult.ForeColor = Color.Red;
}
VB.NET Code


Imports System.Drawing
Imports System.IO
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

End Sub
Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim filename As String = txtName.Text
Dim path As String = "E:\" & filename
Dim file As New FileInfo(path)
If file.Exists Then
file.Delete()
lblResult.Text = filename & " file deleted successfully"
lblResult.ForeColor = Color.Green
Else
lblResult.Text = filename & " file not exists in filepath"
lblResult.ForeColor = Color.Red
End If
End Sub
End Class
Demo


Post a Comment

Popular Posts

Recent Posts

Google Analytics