【问题标题】:Need to check connection every method需要检查每种方法的连接
【发布时间】:2023-02-02 16:48:23
【问题描述】:

我需要使用 SSH 实现一个 Linux 文件实用程序类,如下所示:

class LinuxFileOperation
{
    private string ip, username, password;

    public LinuxFileOperation(string ip, string username, string password)
    {
        this.ip = ip;
        this.username = username;
        this.password = password;
    }

    public void CopyFileOnDevice(string remoteFileNameToBeCopied, string remoteFileNameToBePasted)
    {
        using (var sshClient = new SshClient(ip, username, password))
        {
            sshClient.RunCommand($"cp {remoteFileNameToBeCopied} {remoteFileNameToBePasted}");
        }
    }

    public void DeleteFile(string remoteFilePath)
    {
        using (var sftpClient = new SftpClient(ip, username, password))
        {
            sftpClient.DeleteFile(remoteFilePath);
        }
    }

    public bool FileExists(string file)
    {
        using (var sftpClient = new SftpClient(ip, username, password))
        {
            var fileAttr = sftpClient.GetAttributes(file);
            return fileAttr.IsRegularFile;
        }
    }

    public List<string> GetFileList(string fullSearchPath)
    {
        using (var sftpClient = new SftpClient(ip, username, password))
        {
            return sftpClient.ListDirectory(fullSearchPath).Select(s => s.FullName).ToList();
        }
    }
}

几乎所有具有相同代码的方法使用(var sftpClient/sshClient = new SftpClient/SshClient(ip,用户名,密码)). 任何模式都会减少代码?

【问题讨论】:

    标签: c# design-patterns ssh


    【解决方案1】:

    你可以这样做:

    class LinuxFileOperation
    {
    
        private T WithClient<T>(Func<SftpClient, T> action)
        {
            using (var sftpClient = new SftpClient(ip, username, password))
            {
                return action(sftpClient);
            }
        }
    
        public bool FileExists(string file)
        {
            return WithClient(client => client.GetAttributes(file).IsRegularFile);
        }
    }
    

    ...虽然它并没有减少行数。

    您还可以使用 using 声明:

    class LinuxFileOperation
    {
    
        private sftpClient CreateClient() => new SftpClient(ip, username, password)[
    
        public bool FileExists(string file)
        {
            using var client = CreateClient();
            return client.GetAttributes(file).IsRegularFile;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-08
      • 2012-01-05
      • 2010-09-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多