Asp.Net Create Directory Folder On Server In Runtime

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#
using System.IO;
protected void btnCreate_Click(object sender, EventArgs e)
    {
        string directoryPath = Server.MapPath("~/") +txtDirName.Text;
        if (!Directory.Exists(directoryPath))
        {
            Directory.CreateDirectory(directoryPath);
            lblMessage.Text = "Directory created";
        }
        else
            lblMessage.Text = "Directory already exists";
        
    }

We can also create folder on server in another way as
protected void btnCreate_Click(object sender, EventArgs e)
    {
        string directoryPath = Request.PhysicalApplicationPath + txtDirName.Text;
        DirectoryInfo directory = new DirectoryInfo(directoryPath);
        if (!directory.Exists)
        {
            directory.Create();
            lblMessage.Text = "Directory created";
        }
        else
            lblMessage.Text = "Directory already exists";
    }

VB.NET
Protected Sub btnCreate_Click(sender As Object, e As EventArgs)
 Dim directoryPath As String = Server.MapPath("~/") + txtDirName.Text
 If Not Directory.Exists(directoryPath) Then
  Directory.CreateDirectory(directoryPath)
  lblMessage.Text = "Directory created"
 Else
  lblMessage.Text = "Directory already exists"
 End If

End Sub


Download Sample Code


If you like this post than join us or share

Find More Articles