How to Delete directory in Magento 2 Programmatically?

You can delete any directory from the given path programmatically Using Magento 2 without manual delete.

For example, You have created a directory in var folder at a time of developing functionality and in the future, want to delete the directory from the var folder, You can do it using delete() method of WriteInterface.

Magento\Framework\Filesystem\Directory\WriteInterface is useful for reading/write file – folder specific operation in Magento 2.

<?php
namespace Jesadiya\Directory\Model;

use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem\Directory\WriteInterface;

class DeleteDirectory
{
    /**
     * @var Filesystem
     */
    protected $fileSystem;

    /**
     * @var WriteInterface
     */
    protected $deleteDirectory;

    public function __construct(
        Filesystem $fileSystem
    ) {
        $this->directory = $fileSystem->getDirectoryWrite(DirectoryList::VAR_DIR);
    }

    /**
     * Delete folder
     *
     * @return bool
     * @throws LocalizedException
     */
    public function deleteDirectory()
    {
        $logPath = "log/shipping";
        $deleteDirectory = $this->directory->delete($logPath);

        return $deleteDirectory;
    }
}

The shipping module will be removed from the given path. You need to pass your Path of the folder, which you want to delete from the system.

Output:
True for successful delete directory.