How to fix ERROR_DIR_NOT_EMPTY

Description

The directory is not empty.

Causes

This error occurs when an attempt is made to delete a directory that contains files or subdirectories:

  • Directory contains visible files or folders.
  • Directory contains hidden or system files.
  • Directory contains subdirectories with content.
  • File permissions preventing access to directory contents.
  • Open file handles preventing deletion.
  • Applications currently accessing files in the directory.

Solutions

Remove Directory Contents

Ensure the directory is empty before attempting to delete it:

  • Delete all files in the directory first.
  • Remove all subdirectories and their contents.
  • Check for and remove hidden files and folders.
  • Empty the Recycle Bin if files were moved there.

Use Recursive Delete Operations

Implement recursive deletion to remove directory contents:

  • Use command-line tools with recursive options (e.g., rmdir /s).
  • Implement recursive directory deletion in your application.
  • Use file management utilities that support recursive deletion.

Check for Hidden Files

Ensure hidden and system files are visible and removed:

  • In File Explorer, enable "Show hidden files, folders, and drives".
  • Enable "Show protected operating system files" to see system files.
  • Use command-line tools to list all files including hidden ones (dir /a).
  • Delete hidden files before attempting to remove the directory.

Close Open File Handles

Ensure no applications have files open in the directory:

  • Close all applications that might be accessing files in the directory.
  • Use Process Explorer or similar tools to identify open file handles.
  • Terminate processes with open handles if necessary.
  • Reboot the system if files remain locked.

Check Permissions

Verify you have necessary permissions to delete the directory and its contents:

  • Right-click the directory and check properties/security settings.
  • Take ownership of the directory if needed.
  • Ensure you have delete permissions for all contained files.
  • Run the operation with administrator privileges if required.

Use Command-Line Tools

Use command-line tools for stubborn directories:

rmdir /s /q "C:\path\to\directory"
  • The /s flag removes all subdirectories and files.
  • The /q flag performs a quiet deletion without prompting.

Alternative: Move and Delete

If direct deletion fails, try moving the directory first:

  • Move the directory to a different location.
  • Attempt deletion from the new location.
  • This can sometimes bypass file locking issues.