Creating and Deleting Folders using ASP.NET 2.0 and C#.NET


This tutorial will show you how to create a directory on the disk using ASP.NET 2.0 and C#.NET 

The .NET Framework offers a number of types that makes accessing resources on filesystems easy to use.

To write a simple directory to the disk, we will need to first import the System.IO namespace.
TheSystem.IO namespace contains the CreateDirectory() method that we will use to create our directory. and Delete() method that deletes the specified forlder if it is empty. If folder is not empty it will through a runtime error.

There is also another method to create and delete folders in C#.Net.

The DirectoryInfo Class of System.IO namespace provide number of method to organise files and folders.

// This Code Creates the Folder with specified name

  

protected void btnCreateFolder_Click(object sender, EventArgs e)

{

    DirectoryInfo thisFolder = new DirectoryInfo(Server.MapPath("FolderName"));

  

    if (!thisFolder.Exists)

    {

        thisFolder.Create();

    }

}

  

// This Code Deletes the Folder with specified name, if it is empty.

  

protected void btnDeleteFolder_Click(object sender, EventArgs e)

{

    DirectoryInfo thisFolder = new DirectoryInfo(Server.MapPath("FolderName"));

  

    if (thisFolder.Exists)

    {

        thisFolder.Delete();

    }

}