1需要安装winscp,引用dll
2.clsWinScp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinSCP;
namespace ScpDemo
{
public class clsWinScp
{
public string ServerIP { get; set; }
public string UserName { get; set; }
public string Pwd { get; set; }
public clsWinScp(string addr, string user, string password)
{
this.ServerIP = addr;
this.UserName = user;
this.Pwd = password;
}
public bool RetriveFile(string srcPath, string dstPath)
{
try
{
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.Protocol = Protocol.Sftp;
sessionOptions.HostName = ServerIP;
sessionOptions.UserName = UserName;
sessionOptions.Password = Pwd;
sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = true;
//sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:...";
using (Session session = new Session())
{
session.Open(sessionOptions);
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult =
session.GetFiles(srcPath, dstPath, false, transferOptions);
transferResult.Check();
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Download of {0} succeeded" + transfer.FileName);
}
}
return true;
}
catch (Exception)
{
return false;
}
}
public bool PutFile(List<string> srcPath, List<string> destPath)
{
try
{
SessionOptions sessionOptions = new SessionOptions();
sessionOptions.Protocol = Protocol.Sftp;
sessionOptions.HostName = ServerIP;
sessionOptions.UserName = UserName;
sessionOptions.Password = Pwd;
sessionOptions.GiveUpSecurityAndAcceptAnySshHostKey = true;
//sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:...";
using (Session session = new Session())
{
session.Open(sessionOptions);
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
for (int i = 0; i < srcPath.Count; i++)
{
TransferOperationResult transferResult = session.PutFiles(srcPath[i], destPath[i], false, transferOptions);
transferResult.Check();
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Download of {0} succeeded" + transfer.FileName);
}
}
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}