You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重构基于SSH的Linux文件操作类以消除重复代码?

优化SSH/SFTP客户端重复代码的方案

你的代码核心问题是重复实现了客户端的创建、生命周期管理逻辑,最直接的解决方式是提取通用辅助方法,将客户端的初始化、连接、资源释放等固定逻辑封装起来,只让业务操作作为可变部分传入。这种实现思路属于模板方法模式的简化应用,也符合DRY(Don't Repeat Yourself)原则。

具体实现步骤

  1. 在LinuxFileOperation类中添加通用辅助方法,封装SshClient和SftpClient的生命周期管理:
class LinuxFileOperation
{
    private string ip, username, password;

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

    // 封装带返回值的SftpClient操作
    private T ExecuteWithSftpClient<T>(Func<SftpClient, T> operation)
    {
        using (var sftpClient = new SftpClient(ip, username, password))
        {
            sftpClient.Connect(); // 原代码遗漏连接步骤,必须补充才能正常使用
            return operation(sftpClient);
        }
    }

    // 封装无返回值的SftpClient操作(重载)
    private void ExecuteWithSftpClient(Action<SftpClient> operation)
    {
        ExecuteWithSftpClient<object>(client => 
        {
            operation(client);
            return null;
        });
    }

    // 封装SshClient操作
    private void ExecuteWithSshClient(Action<SshClient> operation)
    {
        using (var sshClient = new SshClient(ip, username, password))
        {
            sshClient.Connect(); // 补充连接步骤
            operation(sshClient);
        }
    }
  1. 修改原有业务方法,复用上述辅助方法:
public void CopyFileOnDevice(string remoteFileNameToBeCopied, string remoteFileNameToBePasted)
    {
        ExecuteWithSshClient(client => 
            client.RunCommand($"cp {remoteFileNameToBeCopied} {remoteFileNameToBePasted}")
        );
    }

    public void DeleteFile(string remoteFilePath)
    {
        ExecuteWithSftpClient(client => 
            client.DeleteFile(remoteFilePath)
        );
    }

    public bool FileExists(string file)
    {
        return ExecuteWithSftpClient(client => 
        {
            var fileAttr = client.GetAttributes(file);
            return fileAttr.IsRegularFile;
        });
    }

    public List<string> GetFileList(string fullSearchPath)
    {
        return ExecuteWithSftpClient(client => 
            client.ListDirectory(fullSearchPath).Select(s => s.FullName).ToList()
        );
    }
}

方案优势

  • 彻底消除重复代码,后续新增SSH/SFTP操作时,只需关注具体业务逻辑
  • 统一管理客户端的连接、释放流程,避免遗漏连接步骤或资源泄漏
  • 代码结构更清晰,职责划分明确:辅助方法负责客户端生命周期,业务方法专注文件操作

内容的提问来源于stack exchange,提问作者ever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 09:05:14