In this tutorial you will learn to create folders dynamically in ASP.Net using C# or VB.Net
We'll take here two server controls one is TextBox and another one is Button. Users may enter the name of the folder in the TextBox they want to create and click the button.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="VC.aspx.cs" Inherits="_VC" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>ASP.Net - Create folder dynamically (C# & VB.Net)</title> </head> <body> <form id="form1" runat="server"> <label for="txtFolderName">Enter Folder Name:</label> <asp:TextBox ID="txtFolderName" runat="server"></asp:TextBox> <asp:Button ID="bthCreateFolder" runat="server" Text="Create New Folder" OnClick="bthCreateFolder_Click" /> <asp:Label ID="lblMsg" runat="server"></asp:Label> </form> </body> </html>
Add namespace
using System.IO; // DirectoryInfo
You need to write the following code in button click event.
protected void bthCreateFolder_Click(object sender, EventArgs e) { // Mention the directory name where you want to create sub directories. string strMainFolderPath = Server.MapPath("~/Files/"); //Create a new subfolder in the main folder. string newPath = System.IO.Path.Combine(strMainFolderPath, txtFolderName.Text.Trim()); DirectoryInfo objDirectory = new DirectoryInfo(newPath); if (!objDirectory.Exists) { System.IO.Directory.CreateDirectory(newPath); lblMsg.Text = "Directory saved successfully"; } else lblMsg.Text = "Directory " + newPath + " already exists!"; }
Imports System.IO // DirectoryInfo
Protected Sub btnCreateFolder_Click(sender As Object, e As System.EventArgs) Handles btnCreateFolder.Click ' Mention the folder name where you want to create sub folders. Dim strPath As String = Server.MapPath("~/Files/") 'Create a new subfolder in the main folder. Dim newPath As String = System.IO.Path.Combine(strPath, txtFolderName.Text.Trim()) Dim objDirectory As New DirectoryInfo(newPath) If Not objDirectory.Exists Then System.IO.Directory.CreateDirectory(newPath) lblMsg.Text = "Directory saved successfully" Else lblMsg.Text = (Convert.ToString("Directory ") & newPath) + " already exists!" End If End Sub