网上写c#调用winscp实现的资料很少,且写的不够详细。本人查了下winscp的libraries说明,写了个小工具,供大家参考。
winscp的接口说明地址如下:
WinSCP .NET Assembly and COM Library :: WinSCP
一、先展示一下小工具的界面
1、支持SFTP/FTP/SCP
2、支持文件夹、文件的上传和下载
二、源码地址
源码地址如下:
https://download.csdn.net/download/qq_39385706/89808931
三、代码关键部分
1、配置会话选项
// 配置会话选项sessionOptions = new SessionOptions{// Protocol = Protocol.Scp,HostName = textBox1.Text,UserName = textBox2.Text,Password = textBox3.Text,PortNumber =Convert.ToInt32( textBox4.Text),//SshHostKeyFingerprint = "ssh-rsa 1024 ll0iqW5PjitSqcb1JuI3pHXOhehkMmHLcKRg1Ijm0JY=",// SshHostKeyFingerprint = "ssh-rsa 1024 ZoU0fHT9xO+4QMxSYJlpebu5xgHPilV3wuAk0diF1AQ=",};switch (comboBox3.Text){case "Sftp":sessionOptions.Protocol = Protocol.Sftp;break;case "Scp":sessionOptions.Protocol = Protocol.Scp;break;case "Ftp":sessionOptions.Protocol = Protocol.Ftp;break;default:break;}if (comboBox3.Text.Equals("Sftp") || comboBox3.Text.Equals("Scp")){sessionOptions.AddRawSettings("KEX", "dh-group1-sha1,ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN");}
2、获取目录列表
using (session = new WinSCP.Session()){try{if (Protocol.Equals("Sftp") || Protocol.Equals("Scp")){//sessionOptions.AddRawSettings("KEX", "dh-group1-sha1,ecdh,dh-gex-sha1,dh-group14-sha1,rsa,WARN");string SshHostKeyFingerprint1 = session.ScanFingerprint(sessionOptions, "SHA-256");LogHelper.WriteLog("SshHostKeyFingerprint====" + SshHostKeyFingerprint1);sessionOptions.SshHostKeyFingerprint = SshHostKeyFingerprint1;}// 连接session.Open(sessionOptions);// Upload filestransferOptions.TransferMode = TransferMode.Binary;//获取所有目录remoteDirectoryInfo = session.ListDirectory(remotePath);// remoteDirectoryInfo = session.ListDirectory(".");int fileCount = remoteDirectoryInfo.Files.Count;Console.WriteLine(fileCount);listView2Show(fileCount);}catch (Exception ex){MessageBox.Show(ex.Message);}}
3、上传文件或文件夹
try{using (session = new WinSCP.Session()){// 连接session.Open(sessionOptions);// Upload filestransferOptions.TransferMode = TransferMode.Binary;string localPath = comboBox1.Text + listView1.SelectedItems[0].Text;string remoptejPath = comboBox2.Text;transferResult = session.PutFiles(localPath, remoptejPath, false, transferOptions);// Throw on any errortransferResult.Check();// Print resultsforeach (TransferEventArgs transfer in transferResult.Transfers){Console.WriteLine("Download of {0} succeeded", transfer.FileName);}}}catch (Exception ex){MessageBox.Show(ex.Message);}
4、下载文件或者文件夹
try{using (session = new WinSCP.Session()){// 连接session.Open(sessionOptions);// Upload filestransferOptions.TransferMode = TransferMode.Binary;string srcPath = comboBox2.Text + listView2.SelectedItems[0].Text;string objPath = comboBox1.Text;transferResult = session.GetFiles(srcPath, objPath, false, null);// Throw on any errortransferResult.Check();// Print resultsforeach (TransferEventArgs transfer in transferResult.Transfers){Console.WriteLine("Download of {0} succeeded", transfer.FileName);}listView1Show(comboBox1.Text);}}catch (Exception ex){MessageBox.Show(ex.Message);}