**
C# sftp上传和下载文件
**
1:首先需要下载依赖的动态库
Renci.SshNet.dll
Renci.SshNet.Async.dll
可以通过NuGet下载
也可以 可以关注gzh 爱学习的兔八哥,send消息 sftp 就可以获得动态库
2:创建 sftpHelper类,对文件进行操作
public class SFTPHelper
{
private SftpClient sftp;
public bool Connected { get { return sftp.IsConnected; } }
public SFTPHelper(string ip, string port, string user, string pwd)
{
sftp = new SftpClient(ip, Int32.Parse(port), user, pwd);
}
public bool Connect()
{
try
{
if (!Connected)
{
sftp.Connect();
}
return true;
}
catch (Exception ex)
{
throw new Exception(string.Format("连接SFTP失败:{0}", ex.Message));
}
}
public void Disconnect()
{
try
{
if (sftp != null && Connected)
{
sftp.Disconnect();
}
}
catch (Exception ex)
{
throw new Exception(string.Format("断开SFTP失败:{0}", ex.Message));
}
}
public void Put(string localPath, string remotePath)
{
try
{
using (var file = File.OpenRead(localPath))
{
Connect();
sftp.UploadFile(file, remotePath);
Disconnect();
}
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件上传失败:{0}", ex.Message));
}
}
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));
}
}
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 + 1) && fileSuffix == name.Substring(name.Length - fileSuffix.Length))
{
objList.Add(name);
}
}
return objList;
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件列表获取失败:{0}", ex.Message));
}
}
}
3:接下来就可以在主程序中调用即可。
SFTPHelper sftpUse = new SFTPHelper("127.0.0.1", "22", "root", "123");
sftpUse.Connect();
sftpUse.Get("/root/bankbill/1.txt", @"D:\work\1.txt");
ArrayList tempList = sftpUse.GetFileList("/root/", "txt");
sftpUse.Disconnect();
可以关注gzh 爱学习的兔八哥,send消息 sftp 就可以获得源代码
版权声明:本文为weixin_42181030原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。