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

c# 使用Renci.SshNet.dll操作SFTP总结的更多相关文章

  1. FileUpload 上传文件,并实现c#使用Renci.SshNet.dll实现SFTP文件传输

    fileupload上传文件和jquery的uplodify控件使用方法类似,对服务器控件不是很熟悉,记录一下. 主要是记录新接触的sftp文件上传.服务器环境下使用freesshd搭建好环境后,wi ...

  2. 未能加载文件或程序集“Renci.SshNet, Version=2016.1.0.0, Culture=neutral, PublicKeyToken=……”

    emmmm~ 这是一个让人烦躁有悲伤的问题~ 背景 我也不知道什么原因,用着用着,正好好的,就突然报了这种问题~ 未能加载文件或程序集“Renci.SshNet, Version=2016.1.0.0 ...

  3. C#访问SFTP:Renci.SshNet.Async

    SFTP是SSH File Transfer Protocol的缩写,安全文件传送协议.安全文件传送协议.可以为传输文件提供一种安全的网络的加密方法.sftp 与 ftp 有着几乎一样的语法和功能. ...

  4. sftp上传文件(Renci.SshNet)和代理上传

    引用Renci.SshNet这个 封装的sftp类 public class SFTPHelper { #region 字段或属性 private SftpClient sftp; /// <s ...

  5. .net 操作sftp服务器

    因为项目的需要,整理了一段C#操作sftp的方法. 依赖的第三方类库名称为:SharpSSH 1.1.1.13. 代码如下: 1: using System; 2: using System.Coll ...

  6. Renci.SshNet在Linux运维的应用

    SSH.NET是一个.net的SSH应用库,支持并发.该库最新的代码可以从github上下载下来,比Sharp.SSH更新的频繁.它可以模拟ssh登陆,类似xshell.putty等工具.不过有更多的 ...

  7. jxl.dll操作总结

    1)Jxl是一个开源的Java Excel API项目,通过Jxl,Java可以很方便的操作微软的Excel文档.除了Jxl之外,还有Apache的一个POI项目,也可以操作Excel,两者相比之下: ...

  8. Asp.Net使用org.in2bits.MyXls.dll操作excel的应用

    首先下载org.in2bits.MyXls.dll(自己的在~\About ASP.Net\Asp.Net操作excel) 添加命名空间: using org.in2bits.MyXls;using ...

  9. C#使用OpcNetApi.dll和OpcNetApi.Com.dll操作OPC

    本人学习了一下.Net,恰好,51自学网,又要用这个.而网上很多VC6,VB6,VB .Net的但,很少C#的.现在研究一下,给出例子: 测试平台,是VS2008,KEPServer,OpcNetAp ...

随机推荐

  1. Cesium 学习笔记

    Entity API 1,和 fill属性不太一样,outline没有对应的材质配置,而是用两个独立的属性outlineColor和outlineWidth. 注意outlineWidth属性仅仅在非 ...

  2. vue-cli webpack浅析

    一直对脚手架的webpack配置很感兴趣. 长话短说,先从npm start开始. 打开package.json 找到scripts 可以看到start 运行的是dev, dev 又是从 build/ ...

  3. AOP之proceedingjoinpoint和joinpoint区别(获取各对象备忘)、动态代理机制及获取原理代理对象、获取Mybatis Mapper接口原始对象

    现在AOP的场景越来越多,所以我们有必要理解下和AOP相关的一些概念和机制. import org.aspectj.lang.reflect.SourceLocation; public interf ...

  4. MAVEN项目中include引入静态文件时报错找不到文件

    1. 出现的问题 Fragment "/common/jsp/resource.jsp" was not found at expected path /src/main/weba ...

  5. Navicat Premium 12

    1.win 客户端软件下载: https://www.navicat.com.cn/download/navicat-premium 2.安装 双击安装--点击下一步 我同意--下一步 选择安装路径- ...

  6. JAVA循环的语法

    一,有几种循环的语法 1while. while(循环条件){ 循环操作 } while(循环条件){ 循环操作 } 2.do-while do{ 循环操作 }while(循环条件); do{ 循环操 ...

  7. deep learning入门:感知机

    权重和偏置 import numpy as np # 求x1 and x2 def AND(x1, x2): x = np.array([x1, x2]) w = np.array([0.5, 0.5 ...

  8. Python SQLAlchemy多对多外键关联时表结构

    # 创建多对多表结构 from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.engine import cre ...

  9. 基于Ocelot的gRpcHttp网关

    什么是gRpcHttp网关 通俗的讲就是将gRpc提供的服务以rest api的形式提供出去,不需要再单独的写一个webapi去做这件事. gRpcHttp网关好处 减少不必要代码,减少中间层提高通讯 ...

  10. Linear Regression with machine learning methods

    Ha, it's English time, let's spend a few minutes to learn a simple machine learning example in a sim ...