深圳全飞鸿

标题: C#操作sftp , 通过winSCP [打印本页]

作者: zhgc    时间: 2019-6-27 16:56
标题: C#操作sftp , 通过winSCP
本帖最后由 zhgc 于 2019-6-27 16:59 编辑

定义部分:

  1.        const string FINGER_PRINT = "ssh-rsa 2048 cd:79:eb:e5:e9:2e:d6:a2:9c:79:65:2a:27:c5:1b:ba";
  2.         const string SERVER_IP = "sftp.nagomes.com";
  3.         const string SERVER_USER = "2L4I9I04F";
  4.         const string SERVER_PASSWORD = "";
  5.         const string SERVER_HOME = @"/incomingkeys/";
  6.         Session WisSession = new Session();

  7.         SessionOptions Lab126SessionOptions = new SessionOptions
  8.         {
  9.             Protocol = Protocol.Sftp,
  10.             HostName = SERVER_IP,
  11.             UserName = SERVER_USER,
  12.             SshPrivateKeyPath = @"D:\sftp\private.ppk",
  13.             GiveUpSecurityAndAcceptAnySshHostKey = true,
  14.             SshHostKeyFingerprint = FINGER_PRINT,
  15.         };
复制代码


连接部分:
  1.        private void btnReconnect_Click(object sender, EventArgs e)
  2.         {
  3.             WisSession.Abort();
  4.             WisSession.Dispose();
  5.             WisSession = new Session();
  6.             WisSession.Open(Lab126SessionOptions);
  7.         }
复制代码



文件上传:
  1.         public void PutFile(string sourcePath, string targetPath)
  2.         {
  3.             {
  4.                 string[] files = Directory.GetFiles(sourcePath);
  5.                 if (files.Count() == 0)
  6.                 {
  7.                     return;
  8.                 }
  9.                 TransferOptions options = new TransferOptions();
  10.                 TransferOperationResult tfr;
  11.                 options.TransferMode = TransferMode.Binary;

  12.                 tfr = WisSession.PutFiles(sourcePath + "*", targetPath + @"*", true, options);
  13.                 tfr.Check();
  14.             }
  15.         }
复制代码



目录遍历:
  1.         public List<string> ListFiles(string dir)
  2.         {
  3.             List<string> fileList = new List<string>();
  4.             RemoteDirectoryInfo rd;   
  5.             rd = WisSession.ListDirectory(dir);
  6.             foreach (RemoteFileInfo rf in rd.Files)
  7.             {
  8.                 if (rf.Name.Trim() == "." || rf.Name.Trim() == "..")
  9.                 {
  10.                     continue;
  11.                 }
  12.                 fileList.Add(rf.Name);
  13.             }
  14.             fileList.Sort();

  15.             return fileList;
  16.         }
复制代码



文件下载:
  1.         public void Getfile(string sourcePath, string targetPath)
  2.         {
  3.             TransferOperationResult tfr;
  4.             tfr = WisSession.GetFiles(sourcePath + "*", targetPath + "*", true);
  5.             tfr.Check();
  6.         }
复制代码





欢迎光临 深圳全飞鸿 (http://www.nagomes.com/disc/) Powered by Discuz! X3.2