ASP.NET: Create and Delete Directory or Folder

Introduction

In this article I explain how to create a directory or folder in your application in ASP.Net using C# code.

Requirement

Add the following namespaces in the code behind .cs file:

using System;
using System.IO;

Code.aspx

Here I have taken a text box and button to create a directory or folder and a text box and button to delete a directory or folder. The following is the design to explain the concept of creating and deleting a directory or folder in ASP.Net:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title></title>

    <style type="text/css">

        .auto-style1 {

            background-color: #CCCCCC;

        }

    </style>

</head>

<body>

<form id="form1" runat="server">

<table style="color: #3366CC; background-color: #CCCCCC">

<tr>

<td class="auto-style1">Name to create a directory:</td>

<td><asp:TextBox ID="txt_name" runat="server" /></td>

<td> <asp:Button ID="btn_create" runat="server" Text="Create" Font-Bold="true" onclick="btn_create_Click" /> </td>

</tr>

<tr>

<td class="auto-style1">Name to delete a directory</td>

<td><asp:TextBox ID="txt_Nam1e" runat="server" /></td>

<td> <asp:Button ID="btn_delete" runat="server" Text="Delete" Font-Bold="true" onclick="btn_delete_Click" /> </td>

</tr>

<tr><td colspan="3" class="auto-style1"><asp:Label ID="lbl_output" runat="server" ForeColor="Red" /> </td></tr>

</table>

</form>

</body>

</html>

Code.cs

Write the following code in the .cs page to create a folder or directory on the create button click:

protected void btn_create_Click(object sender, EventArgs e)

{

    string dir_path = Server.MapPath(txt_name.Text);

   //check if any directory exists with same name

   if (!(Directory.Exists(dir_path)))

   {

       Directory.CreateDirectory(dir_path);

       lbl_output.Text = "Created!!";

   }

   else

   {

       lbl_output.Text = "This name is in use please take any other name";

   }

}

Write the following code in the .cs page to delete a folder or directory on the delete button click:

protected void btn_delete_Click(object sender, EventArgs e)

{

    string dird_path = @"D:\" + txt_Nam1e.Text;

    if (Directory.Exists(dird_path))

    {

        DelteDirectory(dird_path);

    }

    else

    {

        lbl_output.Text = "Directory does not exists";

    }

}

Now save all and view the page in the browser; it will work fine.

Up Next
    Ebook Download
    View all
    Learn
    View all