VB.NET version of previous answer
Public Sub DeleteDirectory(ByVal ftp As Ftp, ByVal remotePath As String)
Console.WriteLine("Deleting directory: '{0}'", remotePath)
''# change the directory
ftp.ChangeDirectory(remotePath)
''# delete all files from the remotePath directory
Dim files As FtpList = ftp.GetList()
Dim i As Integer
For i = 0 To files.Count - 1
If (files.Item(i).IsFile) Then
Console.WriteLine("Deleting file: '{0}'", files.Item(i).Name)
ftp.DeleteFile(files.Item(i).Name)
End If
Next i
''# delete all subdirectories in the remotePath directory
For i = 0 To files.Count - 1
If (files.Item(i).IsDirectory) Then
DeleteDirectory(ftp, files.Item(i).Name)
End If
Next i
''# delete this directory
ftp.ChangeDirectory("..")
ftp.RemoveDirectory(remotePath)
End Sub
You can test it with following code:
Sub Main()
Dim ftp As New Ftp()
ftp.Connect("ftpsite")
ftp.Login("username", "password")
Dim homeDir As String = "/incoming"
ftp.ChangeDirectory(homeDir)
''# create a directory structure
CreateDirIfNotExists(ftp, "a")
CreateFilIfNotExists(ftp, "a/a.txt")
CreateFilIfNotExists(ftp, "a/a2.txt")
CreateDirIfNotExists(ftp, "a/aa")
CreateDirIfNotExists(ftp, "a/b")
CreateDirIfNotExists(ftp, "a/b/bb")
CreateFilIfNotExists(ftp, "a/b/bb/file1.txt")
CreateFilIfNotExists(ftp, "a/b/bb/file2.txt")
CreateFilIfNotExists(ftp, "a/b/bb/file3.txt")
CreateDirIfNotExists(ftp, "a/b/bb/bbb")
CreateDirIfNotExists(ftp, "a/b/abc")
Console.WriteLine("------------")
''# delete recursive
DeleteDirectory(ftp, "a")
ftp.Disconnect()
End Sub
Public Sub CreateFilIfNotExists(ByVal ftp As Ftp, ByVal remotepath As String)
If (Not ftp.FileExists(remotepath)) Then
Dim ms As New MemoryStream()
ms.WriteByte(32)
ms.Seek(0, SeekOrigin.Begin)
ftp.PutFile(ms, remotepath)
Console.WriteLine("Created file " + remotepath)
Else
Console.WriteLine("File creation skipped. Already exists. " + remotepath)
End If
End Sub
Public Sub CreateDirIfNotExists(ByVal ftp As Ftp, ByVal remotepath As String)
If (Not ftp.DirectoryExists(remotepath)) Then
Console.WriteLine("Creating directory " + remotepath)
ftp.CreateDirectory(remotepath)
Else
Console.WriteLine("Directory creation skipped. Already exists. " + remotepath)
End If
End Sub
EDIT: Fixed loop boundaries and added test code.