C# Program to Delete Empty and Nonempty Directory

In C#, directories (folders) are used to organize files and other directories on the computer. The Directory class provides static methods for managing directories, while DirectoryInfo provides instance methods for working with specific directories. This article demonstrates how to delete both empty and non-empty directories using C#.

Syntax

The Directory.Delete() method has two overloads for deleting directories

public static void Delete(string path);
public static void Delete(string path, bool recursive);

Parameters

  • path The directory path to delete (string type)

  • recursive true to delete subdirectories and files; false for empty directories only (boolean type)

Directory Deletion Methods Delete(string path) ? Only empty directories ? Throws exception if directory contains files Directory.Delete("C:/temp") Delete(string, bool) ? Empty and non-empty dirs ? recursive = true deletes all contents Directory.Delete("C:/temp", true) Choose method based on whether directory contains files/subdirectories

Deleting Empty Directories

Use Directory.Delete(string path) to delete directories that contain no files or subdirectories

using System;
using System.IO;

class Program {
   static void Main() {
      string emptyDirPath = @"C:\temp\emptyFolder";
      
      // Create an empty directory for demonstration
      if (!Directory.Exists(emptyDirPath)) {
         Directory.CreateDirectory(emptyDirPath);
         Console.WriteLine("Empty directory created: " + emptyDirPath);
      }
      
      // Delete the empty directory
      Directory.Delete(emptyDirPath);
      Console.WriteLine("Empty directory deleted successfully.");
      
      // Verify deletion
      Console.WriteLine("Directory exists: " + Directory.Exists(emptyDirPath));
   }
}

The output of the above code is

Empty directory created: C:\temp\emptyFolder
Empty directory deleted successfully.
Directory exists: False

Deleting Non-Empty Directories

Use Directory.Delete(string path, bool recursive) with recursive = true to delete directories containing files and subdirectories

using System;
using System.IO;

class Program {
   static void Main() {
      string nonEmptyDirPath = @"C:\temp\nonEmptyFolder";
      string filePath = Path.Combine(nonEmptyDirPath, "sample.txt");
      
      // Create directory and file for demonstration
      if (!Directory.Exists(nonEmptyDirPath)) {
         Directory.CreateDirectory(nonEmptyDirPath);
         File.WriteAllText(filePath, "This is sample content.");
         Console.WriteLine("Non-empty directory created with file: " + filePath);
      }
      
      // Delete the non-empty directory with recursive = true
      Directory.Delete(nonEmptyDirPath, true);
      Console.WriteLine("Non-empty directory deleted successfully.");
      
      // Verify deletion
      Console.WriteLine("Directory exists: " + Directory.Exists(nonEmptyDirPath));
   }
}

The output of the above code is

Non-empty directory created with file: C:\temp\nonEmptyFolder\sample.txt
Non-empty directory deleted successfully.
Directory exists: False

Exception Handling

Directory deletion operations can throw several exceptions. Here's how to handle them properly

using System;
using System.IO;

class Program {
   static void Main() {
      string dirPath = @"C:\temp\testFolder";
      
      try {
         // Create a test directory
         Directory.CreateDirectory(dirPath);
         Console.WriteLine("Directory created: " + dirPath);
         
         // Attempt to delete the directory
         Directory.Delete(dirPath);
         Console.WriteLine("Directory deleted successfully.");
      }
      catch (DirectoryNotFoundException) {
         Console.WriteLine("Error: Directory not found.");
      }
      catch (IOException ex) {
         Console.WriteLine("Error: " + ex.Message);
      }
      catch (UnauthorizedAccessException) {
         Console.WriteLine("Error: Access denied.");
      }
      catch (ArgumentException) {
         Console.WriteLine("Error: Invalid path format.");
      }
   }
}

The output of the above code is

Directory created: C:\temp\testFolder
Directory deleted successfully.

Common Exceptions

Exception Type Cause
IOException Directory is not empty (when using single parameter), or files are in use
UnauthorizedAccessException Insufficient permissions to delete the directory
DirectoryNotFoundException The specified directory path does not exist
ArgumentNullException The path parameter is null
PathTooLongException The path exceeds the system-defined maximum length

Conclusion

Use Directory.Delete(path) for empty directories and Directory.Delete(path, true) for directories containing files or subdirectories. Always implement proper exception handling to manage potential errors during directory deletion operations.

Updated on: 2026-03-17T07:04:36+05:30

801 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements