delete folder, directory c#

In order to remove a directory or folder using C#, .Net framework provides System.IO namspace which provides Directory.Delete method.
Directory.Delete
is a static method that gives you easy way to delete or remove folder or directory. Also we can delete directory or folder using DirectoryInfo class of System.IO namespace.

Examples of deleting directory or folder Directory.CreateDirectory:

Following is sample code for deleting or removing directory or folder on root i.e. at C:/ drive

using System.IO;

class DeleteFolder
{
static void Main()
{

// Delete Directory/folder on C:\ Drive.
Directory.Delete("C:\\TestDirectory");
}
}


Sample code to delete 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.Delete();
}
}

Create new folder, directory

create folder c#
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();
    }
    }