Introduction:
This article explains how to delete a file consisting in
your folder. Requirement:
Add below namespaces in .cs file:
using System;
using System.Drawing;
using System.IO;
code.aspx :
I have files in my application folder named “files”. i want
to delete some file from those so first
i bind all file name in to a dropdown list.
Write below code in the .aspx page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>how to delete a file from a folder in asp.net using c#</title>
<style type="text/css">
.auto-style1 {
width: 88px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>Select file to delete</td>
<td class="auto-style1">
<asp:DropDownList ID="DropDownList1" runat="server" Height="16px" Width="88px">
<asp:ListItem>Select file</asp:ListItem>
<asp:ListItem>file1.txt</asp:ListItem>
<asp:ListItem>file2.pdf</asp:ListItem>
<asp:ListItem>file3.doc</asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr><td></td><td class="auto-style1"><asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" /> </td></tr>
<tr><td colspan="2"><asp:Label ID="lbl_output" runat="server"/></td></tr>
</table>
</div>
</form>
</body>
</html>
Code.cs
:
When dropdown have all file names now you can select any
file which you want to delete and click on button “Delete” it ll check if your
file is existing or not if exist it ll delete file else show you a message that
your file is not existing in the lbl_output.
Write below code on the button delete:
protected void btnDelete_Click(object sender, EventArgs e)
{
string file_name = DropDownList1.SelectedItem.Text;
string path = Server.MapPath("files//" + file_name);
FileInfo file = new FileInfo(path);
if (file.Exists)//check
file exsit or not
{
file.Delete();
lbl_output.Text = file_name + " file deleted successfully";
lbl_output.ForeColor = Color.Green;
}
else
{
lbl_output.Text = file_name + " This file does not exists ";
lbl_output.ForeColor = Color.Red;
}
}
Save
all and view the page in browser it ll work fine.
Thanks.
No comments:
Post a Comment