In this post we will see how to create create folder or directory using C# on server to perform some operations dynamically. .Net provides
System.IO namespace to perform operation related to file system.
System.IO namespace also provides ways to create new folder or directory.In order to create a directory or new folder using C#, we can either use
Directory.CreateDirectory method of the
System.IO namespace or we can use
DirectoryInfo class of System.IO namespace.
Directory.CreateDirectory is a static method that gives you easy way to create new folder or new directory. we will see example of creating new directory or folder using Directory.CreateDirectory:
Sample code that shows how to create directory or folder on root i.e. at C:/ drive
usingSystem.IO;
class CreateNewFolder
{
static void Main()
{
// Create new Directory or folder on C:\ Drive.
Directory.CreateDirectory("C:\\TestDirectory");
}
}
We can also add subfolders to the existing folder, so below C# code shows how to create subdirectory or sub folder in existing folder.
using System.IO;
class CreateNewFolder
{
static void Main()
{
// Create new Directory or folder on C:\ Drive.
Directory.CreateDirectory("C:\\TestDirectory\\SubFolder");
}
}
There are also alternative ways to create sub directory or sub folders. We can create directory or folder using
DirectoryInfo class of System.IO namespace.
Sample code to create directory using System.IO DirectoryInfo class
using System.IO;
class CreateNewFolder
{
static void Main()
{
// Get Directory info or folder info.
DirectoryInfo dir = new DirectoryInfo(@"c:\TestDirectory");
dir.create();
}
}