.net 如何连接linux上传下载文件?
1.net连接linux上传下载文件可以通过scp命令来实现,首先需要我们引入“Renci.SshNet.dll”
1 public class SCPOperation 2 { 3 private ScpClient ssh; 4 5 /// <summary> 6 /// SCP连接状态 7 /// </summary> 8 public bool Connected { get { return ssh.IsConnected; } } 9 10 /// <summary> 11 /// 构造方法 12 /// </summary> 13 /// <param name="ip">IP</param> 14 /// <param name="port">端口</param> 15 /// <param name="user">用户名</param> 16 /// <param name="pwd">密码</param> 17 public SCPOperation(string ip, string port, string user, string pwd) 18 { 19 ssh = new ScpClient(ip, Int32.Parse(port), user, pwd); 20 } 21 22 /// <summary> 23 /// 连接SCP 24 /// </summary> 25 /// <returns>true成功</returns> 26 public bool Connect() 27 { 28 try 29 { 30 if (!Connected) 31 { 32 ssh.Connect(); 33 } 34 return true; 35 } 36 catch (Exception ex) 37 { 38 throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message)); 39 } 40 } 41 42 /// <summary> 43 /// 断开SCP 44 /// </summary> 45 public bool Disconnect() 46 { 47 try 48 { 49 if (ssh != null && Connected) 50 { 51 ssh.Disconnect(); 52 } 53 return true; 54 } 55 catch (Exception ex) 56 { 57 throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message)); 58 } 59 } 60 61 /// <summary> 62 /// SCP上传文件 63 /// </summary> 64 /// <param name="localPath">本地路径</param> 65 /// <param name="remotePath">远程路径</param> 66 public int Upload(string localPath, string remotePath) 67 { 68 try 69 { 70 FileInfo file = new FileInfo(localPath); 71 Connect(); 72 ssh.Upload(file, remotePath); 73 Disconnect(); 74 return 1; 75 } 76 catch (Exception ex) 77 { 78 throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message)); 79 return 0; 80 } 81 } 82 83 /// <summary> 84 /// SCP获取文件 85 /// </summary> 86 /// <param name="remotePath">远程路径</param> 87 /// <param name="localPath">本地路径</param> 88 public void Get(string remotePath, string localPath) 89 { 90 try 91 { 92 Connect(); 93 DirectoryInfo localdir = new DirectoryInfo(localPath); 94 ssh.Download(remotePath, localdir); 95 Disconnect(); 96 } 97 catch (Exception ex) 98 { 99 throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message)); 100 } 101 102 } 103 104 }
2.调用测试:
1 string host = "192.168.1.1"; 2 string user = "root"; 3 string pwd = "koolshare"; 4 string port = "22"; 5 string remotePath = "/tmp/"; 6 string localPath = @"d:/test.txt"; 7 SCPOperation scpClinet = new SCPOperation(host, port, user, pwd); 8 bool isSuccess = scpClinet.Connect(); 9 if (isSuccess) 10 { 11 Console.WriteLine("connect success"); 12 scpClinet.Put(localPath, remotePath); 13 } 14 else 15 { 16 Console.WriteLine("failed"); 17 }