Categories
Asp, Asp.net

How to Create a directory using ASP.NET and C#

How to Create a directory using ASP.NET and C#

In this tutorial we will learn How to Create a directory using ASP.NET and C#. To create a directory on the disk, first we will need to import the System.IO namespace. The System.IO namespace contains the CreateDirectory() method that we will use to create our directory. In previous post we have discussed about How To Print GridView in Asp.Net Using C#.

We take one button and on click of button we create directory to our file system. Here we have taken one text box to input the directory name. This tutorial will help us in dynamically creating directories.

How to Create a directory using ASP.NET and C# Design:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to Create a directory using ASP.NET 2.0 and C#</title>
<style type="text/css">
body {
width: 980px;
margin: 0px auto;
text-align: center;
padding-top: 50px;
font-size: 20px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="cdirtxt" runat="server"></asp:TextBox>
<br />
<asp:Button ID="cdir" Text="Create Directory" OnClick="cdir_Click" runat="server" />
<br />
<asp:Label ID="lblstatus" runat="server"></asp:Label>
<br /><br />
<br /><br />
All rights reserved by <a href="http://www.hightechnology.in">www.Hightechnology.in</a> |
Hosting partner <a href="http://www.grootstech.com" target="_blank">Grootstech</a>   
</div>
</form>
</body>
</html>

How to Create a directory using ASP.NET and C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void cdir_Click(object sender, EventArgs e)
    {
        try
        {
            Directory.CreateDirectory(MapPath(".") + "\\" + cdirtxt.Text);
            lblstatus.Text = "Directory Created Successfully";
        }
        catch (Exception ex)
        {
            lblstatus.Text = ex.Message;
        }
    }
}