使用 WinSCP .NET 程序集删除目录

Delete directory with WinSCP .NET assembly

有问题导致找不到它:

  1. 如何检查目录是否包含任何内容,例如文件夹或文件,无论...还是空的

  2. 如何删除空目录?

  3. 如何删除目录,即使有内容。

例如,我使用以下函数创建目录:

Public Sub CreateDirectory(path As String)
    If session IsNot Nothing Then
        session.CreateDirectory(path)
    End If
End Sub

日志文件为 :

> 2015-10-05 11:11:13.010 MLST /\MainFolder 2014\ANIA
< 2015-10-05 11:11:13.104 550 MLST command failed: No such file or directory.
. 2015-10-05 11:11:13.104 Could not retrieve file information
< 2015-10-05 11:11:13.104 Script: Can't get attributes of file '\MainFolder 2014\ANIA'.
< 2015-10-05 11:11:13.104 Script: Could not retrieve file information

< 2015-10-05 11:11:13.104 MLST command failed: No such file or directory.
. 2015-10-05 11:11:13.104 Script: Failed

要检查目录中是否有任何文件,请使用 Session.EnumerateRemoteFiles method:

Dim anyFile As Boolean =
    mySession.EnumerateRemoteFiles(
        path, Nothing, EnumerationOptions.MatchDirectories).Any()

自 WinSCP 5.9 起支持 Session.EnumerateRemoteFiles


对于旧版本的 WinSCP,使用 Session.ListDirectory 列出目录内容并过滤掉 ... 条目:

Dim anyFile As Boolean =
    mySession.ListDirectory(path).Files.
    Where(Function(file) (file.Name <> "..") And (file.Name <> ".")).
    Any()

要删除任何目录,无论是否为空,请使用 Session.RemoveFiles:

session.RemoveFiles(RemotePath.EscapeFileMask(path))