简体   繁体   中英

SSH.Net library and use of wild card

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();
}

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM