Skip to content
NewRedesigned blogFeedback
Jigar Karangiya

How to delete file in magento 2 programmatically

Hello Magento Devs, In today’s tutorial, i’m going to show you how you can delete file in magento 2 programatically.

How to delete file in magento 2 programmatically
Written by
JKJigar Karangiya
Published
Reading time
1 min read

Jigar Karangiya · · 1 min read

Hello Magento Devs,

In today’s tutorial, i’m going to show you how you can delete file in magento 2 programatically.

Method 1 : Using injecting class in constructor

We can delete file in magento standard way by injecting below class in constructor.

text
\Magento\Framework\Filesystem\Driver\File $file

Let’s understand it by a simple example. (opens in new tab)

php
<?php
namespace Jigar/DeleteTutorial/Block;
 
use Magento\Backend\App\Action;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Filesystem;
use Magento\Framework\App\Filesystem\DirectoryList;
 
class Delete extends Action
{
    protected $fileSystem;
 
    protected $file;
 
    public function __construct(
        Filesystem $fileSystem,
        File $file
    )
    {
        $this->fileSystem = $fileSystem;
        $this->file = $file;
    }
 
    public function delete()
    {
        $fileName= "your_filename.csv";
        $mediaRootDir = $this->fileSystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
        if ($this->file->isExists($mediaRootDir . $fileName)) {
            $this->file->deleteFile($mediaRootDir . $fileName);
        }
       
    }
}

Method 2 : Directly using object manager (Not Recommended)

php
$fileName= "your_filename.csv";
 
$file = $this->_objectManager->get('Magento\Framework\Filesystem\Driver\File');
 
$mediaDirectory = $this->_objectManager->get('Magento\Framework\Filesystem')->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
 
$mediaRootDir = $mediaDirectory->getAbsolutePath();
 
if ($file->isExists($mediaRootDir . $fileName))  {
    $file->deleteFile($mediaRootDir . $fileName);
}

That’s it, now you know how to delete any file in magento standard way.

Thanks for reading !!

Keep reading
All posts

01 · 10 min · Shares Adobe Commerce Core

Adobe Commerce Agentic Capabilities, Q4 2026

Five agentic releases for Adobe Commerce: LLM product discovery, Brand Visibility, the Shopper MCP server, Brand Concierge, and Experience Workspace. What each one does, which editions get it, and when.

10 min

03 · 3 min · Shares Adobe Commerce Core

Conditions for Collections in Magento 2

Collections in Magento 2 (Now Adobe Commerce), are among the most powerful tools for retrieving and manipulating data directly from the database.

3 min

Newsletter

New Magento tutorials, straight to your inbox

Code examples, performance tips, and fixes for common Magento issues. No spam.

Subscribe