我需要使用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();
}
}
关于c# - SSH.Net库和通配符的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22308447/