1、操作类

    /// <summary>
/// SFTP操作类
/// </summary>
public class SFTPHelper
{
#region 字段或属性
private SftpClient sftp;
private string cmsimagesIP = ConfigurationManager.AppSettings["cmsimagesIP"].ToString();
private string cmsimagesName = ConfigurationManager.AppSettings["cmsimagesName"].ToString();
private string cmsimagesPwd = ConfigurationManager.AppSettings["cmsimagesPwd"].ToString(); /// <summary>
/// SFTP连接状态
/// </summary>
public bool Connected { get { return sftp.IsConnected; } }
#endregion #region 构造
/// <summary>
/// 构造
/// </summary>
public SFTPHelper()
{
sftp = new SftpClient(cmsimagesIP, , cmsimagesName, cmsimagesPwd);
}
#endregion #region 连接SFTP
/// <summary>
/// 连接SFTP
/// </summary>
/// <returns>true成功</returns>
public bool Connect()
{
try
{
if (!Connected)
{
sftp.Connect();
}
return true;
}
catch (Exception ex)
{
// TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("连接SFTP失败,原因:{0}", ex.Message));
throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message));
}
}
#endregion #region 断开SFTP
/// <summary>
/// 断开SFTP
/// </summary>
public void Disconnect()
{
try
{
if (sftp != null && Connected)
{
sftp.Disconnect();
}
}
catch (Exception ex)
{
// TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("断开SFTP失败,原因:{0}", ex.Message));
throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message));
}
}
#endregion #region SFTP上传文件
/// <summary>
/// SFTP上传文件
/// </summary>
/// <param name="localPath">本地路径</param>
/// <param name="remotePath">远程路径</param>
public void Put(string localPath, string remotePath, string fileName)
{
try
{
using (var file = File.OpenRead(localPath))
{
Connect();
//判断路径是否存在
if (!sftp.Exists(remotePath))
{
sftp.CreateDirectory(remotePath);
}
sftp.UploadFile(file, remotePath + fileName);
Disconnect();
}
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
}
}
#endregion #region SFTP获取文件
/// <summary>
/// SFTP获取文件
/// </summary>
/// <param name="remotePath">远程路径</param>
/// <param name="localPath">本地路径</param>
public void Get(string remotePath, string localPath)
{
try
{
Connect();
var byt = sftp.ReadAllBytes(remotePath);
Disconnect();
File.WriteAllBytes(localPath, byt);
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
} }
#endregion #region 获取SFTP文件列表
/// <summary>
/// 获取SFTP文件列表
/// </summary>
/// <param name="remotePath">远程目录</param>
/// <param name="fileSuffix">文件后缀</param>
/// <returns></returns>
public ArrayList GetFileList(string remotePath, string fileSuffix)
{
try
{
Connect();
var files = sftp.ListDirectory(remotePath);
Disconnect();
var objList = new ArrayList();
foreach (var file in files)
{
string name = file.Name;
if (name.Length > (fileSuffix.Length + ) && fileSuffix == name.Substring(name.Length - fileSuffix.Length))
{
objList.Add(name);
}
}
return objList;
}
catch (Exception ex)
{
// TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件列表获取失败,原因:{0}", ex.Message));
throw new Exception(string.Format("SFTP文件列表获取失败,原因:{0}", ex.Message));
}
}
#endregion #region 移动SFTP文件
/// <summary>
/// 移动SFTP文件
/// </summary>
/// <param name="oldRemotePath">旧远程路径</param>
/// <param name="newRemotePath">新远程路径</param>
public void Move(string oldRemotePath, string newRemotePath)
{
try
{
Connect();
sftp.RenameFile(oldRemotePath, newRemotePath);
Disconnect();
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件移动失败,原因:{0}", ex.Message));
}
}
#endregion #region 删除SFTP文件
public void Delete(string remoteFile)
{
try
{
Connect();
sftp.Delete(remoteFile);
Disconnect();
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
}
}
#endregion #region 创建目录
/// <summary>
/// 循环创建目录
/// </summary>
/// <param name="remotePath">远程目录</param>
private void CreateDirectory(string remotePath)
{
try
{
string[] paths = remotePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string curPath = "/";
for (int i = ; i < paths.Length; i++)
{
curPath += paths[i];
if (!sftp.Exists(curPath))
{
sftp.CreateDirectory(curPath);
}
if (i < paths.Length - )
{
curPath += "/";
}
}
}
catch (Exception ex)
{
throw new Exception(string.Format("创建目录失败,原因:{0}", ex.Message));
}
}
#endregion
}

2、调用

     /// <summary>
/// 上传图片
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public ActionResult UploadImage(int HotelID, HttpPostedFileBase file)
{
if (file == null)
{
return Json(new { code = , message = "请先选择图片" });
}
string batchNo = System.Guid.NewGuid().ToString();
string fileWebPath = "/upload/" + HotelID + "/";
string directory = Request.MapPath("~" + fileWebPath);
string fileName = batchNo + Path.GetExtension(file.FileName);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string fileFullName = Path.Combine(directory, fileName);
try
{
file.SaveAs(fileFullName);
//上传SFTP
SFTPHelper sftp = new SFTPHelper();
sftp.Put(fileFullName, "/home/cmsimages/ads/cmsimages/choice/" + HotelID + "/", fileName);
return Json(new { code = , message = fileWebPath + fileName });
}
catch (Exception e)
{
return Json(new { code = , message = e.Message });
}
}

3、Renci.SshNet.dll下载链接:

https://download.csdn.net/download/jiduxiaozhang12345/10695019

最新文章

  1. 理解RESTful
  2. 要用于尝试,广东移动间接实现“流量不清零”[bubuko.com]
  3. Android停止运行问题1_layout布局xml问题
  4. How Google TestsSoftware - Part One
  5. Info
  6. WPF学习拾遗(二)TextBlock换行
  7. C# - ADO.Net 调用存储过程
  8. C++ Primer 学习笔记_75_模板与泛型编程 --模板定义
  9. BTE 增强
  10. mac的终端为什么会显示git:(master),如何取消掉?
  11. Vijos 1111 小胖的水果 LCS
  12. volatile特性及内存语义
  13. oracle pl/sql如何定义变量
  14. 死磕 java集合之LinkedBlockingQueue源码分析
  15. Django-用户模块与权限系统相关
  16. python四:函数练习--小白博客
  17. js基本类型存放和对象存放的区别(对象遍历)
  18. Bzoj4558:分类讨论 计算几何 组合数学
  19. 解决Navicat Premium 12 连接oracle数据库出现ORA-28547的问题
  20. 【线段树】HDU 3397 Sequence operation 区间合并

热门文章

  1. vue强制刷新组件
  2. 2019/4/19 wen 线程2
  3. python操作pymysql数据库
  4. Python中 sys.argv[]的用法简明解释
  5. C 语言多线程与锁机制
  6. loj 6008 餐巾计划 - 费用流
  7. time模块和os模块,json模块
  8. iP私网地址
  9. 趋势:flex和grid使布局更简单
  10. echarts 角度渐变环形图心得