In this article I will explain how to delete a folder or directory in C# or VB.Net.
Directory or Folder is an entity that can contain multiple folders or files in it.
Note: A Directory that contains files or folders cannot be deleted hence you will first need to empty the Directory i.e. Delete all the Child Directories and also all the files in the Directory as well the Child Directories.
 
Namespaces
You will need to import the following namespaces
C#
using System.IO;
 
VB.Net
Imports System.IO
 
 
Deleting the Directory its files and Child Directories
The below function will delete the Root Directory and also its files, Child Directories and their files too using recursion.
C#
protected void Page_Load(object sender, EventArgs e)
{
    string path = @"E:\NewFolder\";
    DeleteDirectory(path);
}
 
private void DeleteDirectory(string path)
{
    if (Directory.Exists(path))
    {
        //Delete all files from the Directory
        foreach (string file in Directory.GetFiles(path))
        {
            File.Delete(file);
        }
        //Delete all child Directories
        foreach (string directory in Directory.GetDirectories(path))
        {
            DeleteDirectory(directory);
        }
        //Delete a Directory
        Directory.Delete(path);
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    Dim path As String = "E:\NewFolder\"
    DeleteDirectory(path)
End Sub
 
Private Sub DeleteDirectory(path As String)
    If Directory.Exists(path) Then
        'Delete all files from the Directory
        For Each filepath As String In Directory.GetFiles(path)
            File.Delete(filepath)
        Next
        'Delete all child Directories
        For Each dir As String In Directory.GetDirectories(path)
            DeleteDirectory(dir)
        Next
        'Delete a Directory
        Directory.Delete(path)
    End If
End Sub