SSH.Net 库和通配符的使用 [英] SSH.Net library and use of wild card

查看:51
本文介绍了SSH.Net 库和通配符的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 SSH.NET 登录 SFTP 并删除文件夹中的所有文件,但似乎 SSH.Net 不支持通配符.这是真的吗?有办法解决吗?这是我的代码.

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

这篇关于SSH.Net 库和通配符的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆