How to remove a non-empty folder on an FTP?

Is it possible to remove from the FTP folder is not empty.
or in the first need to delete all the files in the folder?

1 Like

it really depends on which library are you using, each 3rd party library supports a different functionally.

For instance; if you are using builtin .Net Framework WebRequest class, then the answer is simply "NO"

The builtin WebRequest doesn’t support deleting non-empty directories from FTP.

But as you might already know (in case you are using the builtin WebRequest class) then you can actually remove a folder like this:

FtpWebRequest ftp_request = (FtpWebRequest)WebRequest.Create(your_directory_goes_here);
ftp_request.Method = WebRequestMethods.Ftp.RemoveDirectory;
/* And then simply make a call to the web request. */

But this as said previously Will Not delete NON-EMPTY directories.

So the solution would be either to use a 3rd party .Net library that supports deleting directories and contained files in a single call, or otherwise make a recursive call yourself, something like this:

private void delete_ftp_directory(string parent, string path)
    string path_segment = get_next_path_segment(path); /* first valid segment before a separator / or \ */
    string path = advance_path_segment(path); /* update path variable to point to the next segment if any */

    if (ftp_directory_has_files(Path.Combine(parent, path_segment)))
         /* has files delete them all. */
         delete_ftp_directory(parent, path);
    /* Now delete the directory itself */
    ftp_delete_empty_directory(Path.Combine(parent, path_segment));

Hope that gives you an idea of what should be done :slight_smile:

Thanks a lot to your answer,
i really used, .Net Framework WebRequest class.
I solved the problem,
in first requested for FTP file names,
and then delete them and then delete the folder :slight_smile:

1 Like

awesome :slight_smile:
you are always welcome @ivan.norin
If you need anything i’ll be always around.