문제

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();
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top