Thursday, March 28, 2013

In this example i'm explaining how to How To Create Folder Or Directory On Server Dynamically In Runtime Using Asp.Net C# VB.NET. I have place one textbox on the page for folder name to be entered by user and in click event of button directory is created on server.

Asp.NET Create Directory Folder In Server In Runtime


HTML SOURCE OF PAGE
   1:  Directory Name:
   2:  <asp:TextBox ID="txtDirName" runat="server"/>
   3:  <asp:Button ID="btnCreate" runat="server" 
   4:              Text="Create Folder" 
   5:              onclick="btnCreate_Click"/>
   6:  <asp:Label ID="lblMessage" runat="server"/>

Write following code in Click Event of button

Add System.IO namespace in code behind

C#
01using System.IO;
02protected void btnCreate_Click(object sender, EventArgs e)
03    {
04        string directoryPath = Server.MapPath("~/") +txtDirName.Text;
05        if (!Directory.Exists(directoryPath))
06        {
07            Directory.CreateDirectory(directoryPath);
08            lblMessage.Text = "Directory created";
09        }
10        else
11            lblMessage.Text = "Directory already exists";
12 
13    }

We can also create folder on server in another way as
01protected void btnCreate_Click(object sender, EventArgs e)
02    {
03        string directoryPath = Request.PhysicalApplicationPath + txtDirName.Text;
04        DirectoryInfo directory = new DirectoryInfo(directoryPath);
05        if (!directory.Exists)
06        {
07            directory.Create();
08            lblMessage.Text = "Directory created";
09        }
10        else
11            lblMessage.Text = "Directory already exists";
12    }

VB.NET
01Protected Sub btnCreate_Click(sender As Object, e As EventArgs)
02 Dim directoryPath As String = Server.MapPath("~/") + txtDirName.Text
03 If Not Directory.Exists(directoryPath) Then
04  Directory.CreateDirectory(directoryPath)
05  lblMessage.Text = "Directory created"
06 Else
07  lblMessage.Text = "Directory already exists"
08 End If
09 
10End Sub

0 comments:

Post a Comment