Monday 14 October 2013

Create Delete Directory Folder in Asp.net, C#

Design Page Code  :

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Create or Delete Directory/floder in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td><b>Enter File Name to Create:</b></td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
<td> <asp:Button ID="btnCreate" runat="server" Text="Create Directory" Font-Bold="true"onclick="btnCreate_Click" /> </td>
</tr>
<tr>
<td><b>Enter File Name to Delete:</b></td>
<td><asp:TextBox ID="txtdltName" runat="server" /></td>
<td> <asp:Button ID="btnDelete" runat="server" Text="Delete Directory" Font-Bold="true"onclick="btnDelete_Click" /> </td>
</tr>
<tr><td colspan="3"><asp:Label ID="lblResult" runat="server" ForeColor="Red" /> </td></tr>
</table>
</form>
</body>
</html>


Code Behind:

// Create new directory
protected void btnCreate_Click(object sender, EventArgs e)
{
string strpath = @"D:\" + txtName.Text;
//Condition to check if any directory exists with same name
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
lblResult.Text = "Directory Created";
}
else
{
lblResult.Text = "Already Directory Exists with the same name";
}
}
// Delete direcoty or folder
protected void btnDelete_Click(object sender, EventArgs e)
{
string strpath = @"D:\" + txtdltName.Text;
if (Directory.Exists(strpath))
{
RemoveDirectories(strpath);
}
else
{
lblResult.Text = "Directory not exists";
}
}

private void RemoveDirectories(string strpath)
{
//This condition is used to delete all files from the Directory
foreach (string file in Directory.GetFiles(strpath))
{
File.Delete(file);
}
//This condition is used to check all child Directories and delete files
foreach (string subfolder in Directory.GetDirectories(strpath))
{
RemoveDirectories(subfolder);
}
Directory.Delete(strpath);
lblResult.Text = "Directory deleted";
}

No comments:

Post a Comment