Friday, 17 May 2013

ASP.Net: Create/delete directory or folder | Neha Sharma



Introduction:

In this article I explain how to create a directory or folder in your application in asp.net using c# code.

Requirement:

Add below 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 .Below is design to explain the concept of create and delete 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 below code in .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 below code in .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 browser it ll work fine.

Thanks

No comments:

Post a Comment

Which Game Engine you should choose | Neha Sharma

Unity3D and Unreal Engine are only 2 Game engine which executes an indispensable position in Game Industry. The choice of the engine must ...