How do I delete an FTP directory that has contents?

You'll need to use recursion to traverse the directories and sub-directories. They key is setting the RemotePath to the 'current' directory and calling ListDirectory() before attempting to remove anything.

You'll also need to make sure that you know the item you're trying to delete is a directory. The code below presumes that you have already identified a directory to delete.

*Note: it may be prudent to initially catch the error and warn the user that they're about to delete a non-empty directory.

Calling the recursive function: //I want to delete someFolder from ftp1.RemotePath string oldPath = ftp1.RemotePath; //call recursive helper function clearDirectory(ftp1.RemotePath + "/" + someFolder);
An example of a recursive function that will delete the non-directory items in the directory, then recursive delete the directories. 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); } } }

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