public class SFTPHelper
{
#region 字段或属性 private readonly SftpClient _sftp; /// <summary>
/// SFTP连接状态
/// </summary>
public bool Connected
{
get
{
return _sftp.IsConnected;
}
} #endregion #region 构造函数 /// <summary>
/// 构造1
/// </summary>
/// <param name="ip">IP</param>
/// <param name="port">端口</param>
/// <param name="user">用户名</param>
/// <param name="pwd">密码</param>
public SFTPHelper(string ip, string port, string user, string pwd)
{
_sftp = new SftpClient(ip, Int32.Parse(port), user, pwd);
} /// <summary>
/// 构造2
/// </summary>
/// <param name="host">服务器地址</param>
/// <param name="user">用户名</param>
/// <param name="pwd">密码</param>
public SFTPHelper(string host, string user, string pwd)
{
_sftp = new SftpClient(host, user, pwd);
} #endregion #region 连接SFTP /// <summary>
/// 连接SFTP
/// </summary>
/// <returns>true成功</returns>
private void Connect()
{
if (!Connected)
{
_sftp.Connect();
}
} #endregion #region 断开SFTP /// <summary>
/// 断开SFTP
/// </summary>
private void Disconnect()
{
if (_sftp != null && Connected)
{
_sftp.Disconnect();
}
} #endregion #region SFTP上传文件 /// <summary>
/// SFTP上传文件
/// </summary>
/// <param name="localPath">本地路径</param>
/// <param name="remotePath">远程路径</param>
public void UploadFile(string localPath, string remotePath)
{
using (var fileStream = File.OpenRead(localPath))
{
Connect();
_sftp.UploadFile(fileStream, remotePath);
Disconnect();
}
} #endregion #region SFTP下载文件 /// <summary>
/// SFTP下载文件
/// </summary>
/// <param name="remotePath">远程路径</param>
/// <param name="localPath">本地路径</param>
public void DownloadFile(string remotePath, string localPath)
{
Connect();
var byt = _sftp.ReadAllBytes(remotePath);
Disconnect();
File.WriteAllBytes(localPath, byt);
} #endregion
}