vb.netwinscpwinscp-net

Delete directory with WinSCP .NET assembly


Have to questions cause can't find it:

  1. How to check if directory contains anything e.g folder or files, whatever... or is it empty

  2. How to remove an empty directory?

  3. How to remove a directory even if there is content.

For instance for creating directory I am using below function:

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

Log file as requested in comment:

> 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

Solution

  • To check, if there are any files in a directory, use the Session.EnumerateRemoteFiles method:

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

    The Session.EnumerateRemoteFiles is supported since WinSCP 5.9.


    With older versions of WinSCP, list directory contents using the Session.ListDirectory and filter out the this (.) and parent (..) entries:

    Dim anyFile As Boolean =
        mySession.ListDirectory(path).Files.
        Where(Function(file) Not file.IsThisDirectory And Not file.IsParentDirectory).
        Any()
    

    To remove any directory, be it empty or not, use Session.RemoveFiles:

    session.RemoveFiles(RemotePath.EscapeFileMask(path))