IT序号网

c#之SSH.Net库和通配符的使用

soundcode 2025年05月04日 编程语言 150 0

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

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

请您参考如下方法:

我也不太喜欢使用该库的通配符。我刚刚创建了一个扩展方法(简单):

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


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!