如何重构基于SSH的Linux文件操作类以消除重复代码?
优化SSH/SFTP客户端重复代码的方案
你的代码核心问题是重复实现了客户端的创建、生命周期管理逻辑,最直接的解决方式是提取通用辅助方法,将客户端的初始化、连接、资源释放等固定逻辑封装起来,只让业务操作作为可变部分传入。这种实现思路属于模板方法模式的简化应用,也符合DRY(Don't Repeat Yourself)原则。
具体实现步骤
- 在
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); } }
- 修改原有业务方法,复用上述辅助方法:
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
相关产品推荐
相关产品推荐

