Create Folder On Server create folder on server.

Here we will see how to create folder on server dynamically. If directory already exists on server we will notify user about existence of directory on server. System.IO namespace provides directory and file operations classes. C# create folder.

using System;
using System.IO;

public partial class Dynamic_Directory : System.Web.UI.Page
   protected void Button1_Click(object sender, EventArgs e)

    string serverDirectory = Server.MapPath("uploads");

    string folderName = TextBox1.Text;

    string directoryPath = serverDirectory + @"\" + folderName;

    if (!Directory.Exists(directoryPath))
      lblMessage.Text = "Directory created on server.";
      lblMessage.Text = "Directory already exists.";
} aspx code dynamic create directory example.

    <form id="form1" runat="server">
        Input Folder name:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Create" OnClick="Button1_Click" />
        <br />
        <asp:Label ID="lblMessage" runat="server"></asp:Label></div>
</body> create directory dynamically on server [] example.

Imports System
Imports System.IO

Public Partial Class Dynamic_Directory
	Inherits System.Web.UI.Page
	Protected Sub Button1_Click(sender As Object, e As EventArgs)

		Dim serverDirectory As String = Server.MapPath("uploads")

		Dim folderName As String = TextBox1.Text

		Dim directoryPath As String = serverDirectory + "\" + folderName

		If Not Directory.Exists(directoryPath) Then
			lblMessage.Text = "Directory created on server."
			lblMessage.Text = "Directory already exists."
		End If
	End Sub
End Class

Description: First you need to map the virtual path with physical path. We have created uploads folder on server at root. Server.MapPath is used to get physical location of file or directory. All dynamically created folder will resides under this uploads folder.

Directory.Exists is static method of directory class. It checks an existence of directory on server. If it already exists, we can tell user to choose other name.

CreateDirecory is static method of Directory class. It accepts fully qualified directory path and creates new directory at specified location.

Note: Your runtime must have rights to create directory on server. Give user under which worker process is running a write permission.


My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.

I'm Satalaj.