How to Delete a Non-Empty Directory in FTP


FTP does not allow deleting a non-empty directory directly. To remove it, all files and subdirectories must be deleted first, and then the directory itself can be removed.

To do this, set RemotePath to the target directory and call ListDirectoryLong to retrieve its contents. Delete all files, then process any subdirectories, and finally remove the directory once it is empty.

//I want to delete someFolder from ftp1.RemotePath
string oldPath = ftp1.RemotePath;
//call recursive helper function
clearDirectory(ftp1.RemotePath + "/" + someFolder);

The following helper function processes the directory by deleting files first, then handling subdirectories, and finally removing the directory once it is empty:

private void clearDirectory(string path)
{
    //list the current contents "path"
    ftp1.RemotePath = path;
    ftp1.RemoteFile = "";
    ftp1.ListDirectoryLong();
    //delete everything that isn't a directory
    for (int i = 0; i < ftp1.DirList.Count; i++)
    {
        if (!ftp1.DirList[i].IsDir)
            ftp1.DeleteFile(ftp1.DirList[i].FileName);
    }
    //re-list the current contents of "path"
    ftp1.RemotePath = path;
    ftp1.RemoteFile = "";
    ftp1.ListDirectoryLong();
    //recurse through any directories 
    for (int i = 0; i < ftp1.DirList.Count; i++){
        if (ftp1.DirList[i].IsDir)
        {
            clearDirectory(ftp1.RemotePath + "/" + ftp1.DirList[i].FileName);
            ftp1.RemotePath = path;
            ftp1.RemoteFile = "";
            ftp1.ListDirectoryLong();
        }
    }
    //remove the now empty directories within "path"
    for (int i = 0; i < ftp1.DirList.Count; i++)
    {
        if (ftp1.DirList[i].IsDir)
        {
            ftp1.RemoveDirectory(ftp1.DirList[i].FileName);
        }
    }
}

Note: Ensure the target is a directory before deletion. It is also recommended to handle errors to avoid accidental deletion of non-empty or incorrect directories.

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.