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:

  1. using System;  
  2. 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:

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head>  
  3. <title></title>  
  4.     <style type="text/css">  
  5.         .auto-style1 {  
  6.             background-color: #CCCCCC;  
  7.         }  
  8.     </style>  
  9. </head>  
  10. <body>  
  11. <form id="form1" runat="server">  
  12. <table style="color: #3366CC; background-color: #CCCCCC">  
  13. <tr>  
  14. <td class="auto-style1">Name to create a directory:</td>  
  15. <td><asp:TextBox ID="txt_name" runat="server" /></td>  
  16. <td> <asp:Button ID="btn_create" runat="server" Text="Create" Font-Bold="true" onclick="btn_create_Click" /> </td>  
  17. </tr>  
  18. <tr>  
  19. <td class="auto-style1">Name to delete a directory</td>  
  20. <td><asp:TextBox ID="txt_Nam1e" runat="server" /></td>  
  21. <td> <asp:Button ID="btn_delete" runat="server" Text="Delete" Font-Bold="true" onclick="btn_delete_Click" /> </td>  
  22. </tr>  
  23. <tr><td colspan="3" class="auto-style1"><asp:Label ID="lbl_output" runat="server" ForeColor="Red" /> </td></tr>  
  24. </table>  
  25. </form>  
  26. </body>  
  27. </html> 

Code.cs

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

 

  1. protected void btn_create_Click(object sender, EventArgs e)  
  2. {  
  3.     string dir_path = Server.MapPath(txt_name.Text);  
  4.    //check if any directory exists with same name  
  5.    if (!(Directory.Exists(dir_path)))  
  6.    {  
  7.        Directory.CreateDirectory(dir_path);  
  8.        lbl_output.Text = "Created!!";  
  9.    }  
  10.    else  
  11.    {  
  12.        lbl_output.Text = "This name is in use please take any other name";  
  13.    }  
  14. }

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

  1. protected void btn_delete_Click(object sender, EventArgs e)  
  2. {  
  3.     string dird_path = @"D:\" + txt_Nam1e.Text;  
  4.     if (Directory.Exists(dird_path))  
  5.     {  
  6.         DelteDirectory(dird_path);  
  7.     }  
  8.     else  
  9.     {  
  10.         lbl_output.Text = "Directory does not exists";  
  11.     }  
  12. } 

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


Similar Articles