Question

I need to login to SFTP with SSH.NET and delete all files in the folder, but it seem like SSH.Net does not support wild card. Is it true? Is there way to fix it? Here is my code.

using (SftpClient sftpClient = new SftpClient(server, port, username, password))
{
    foreach (var d in sftpClient.ConnectionInfo.Encryptions.Where(p => p.Key != "blowfish-cbc").ToList())
    {
        sftpClient.ConnectionInfo.Encryptions.Remove(d.Key);
    }

    sftpClient.Connect();
    sftpClient.DeleteFile("/outgoing/*.*");
    sftpClient.Disconnect();
}
Was it helpful?

Solution

I haven't had much luck with wildcards using this library, either. I just ended up creating an extension method (simplistic):

public static IEnumerable<SftpFile> ListDirectoryWC(this SftpClient client, string pattern, Func<SftpFile,bool> includeTest=null)
{
    string directoryName = (pattern[0] == '/' ? "" : "/") + pattern.Substring(0, pattern.LastIndexOf('/'));
    string regexPattern = pattern.Substring(pattern.LastIndexOf('/') + 1)
            .Replace(".", "\\.")
            .Replace("*", ".*")
            .Replace("?", ".");
    Regex reg = new Regex('^' + regexPattern + '$');

    var results = client.ListDirectory(String.IsNullOrEmpty(directoryName) ? "/" : directoryName)
        .Where(e => reg.IsMatch(e.Name) && (includeTest == null || includeTest(e)));
    return results;
}

public static void DeleteFileWC(this SftpClient client, string pattern, Func<SftpFile,bool> includeTest=null)
{
    foreach(var file in client.ListDirectoryWC(pattern, includeTest))
    {
        file.Delete();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top