1、安装SSH.NET类库程序包
Install-Package SSH.NET -Version 2020.0.0-beta1
更多版本:https://www.nuget.org/packages/SSH.NET/
2、代码:
using System;
using System.IO;
using System.Threading.Tasks;
using System.Collections.Generic;
using Renci.SshNet;
using Renci.SshNet.Sftp;
namespace Com.BaiGe.CallCode
{
public class FtpHelper
{
/**
参数一:directory指的是要上传到sftp的具体目录/文件夹中
参数二:pdfFile指的是要上传的文件路径
*/
public int Upload(string directory, string pdfFile)
{
const int port = 22;
const string host = "xxx";
const string username = "xxx";
const string password = "xxx";
try
{
using (SftpClient client = new SftpClient(host, port, username, password))
{
client.Connect();
client.ChangeDirectory(directory);
int beforeCount = GetFileCount(client, directory);
using (FileStream fileStream = new FileStream(pdfFile, FileMode.Open))
{
client.BufferSize = 4 * 1024;
client.UploadFile(fileStream, Path.GetFileName(pdfFile));
int afterCount = GetFileCount(client, directory);
return afterCount - beforeCount;
}
}
} catch (Exception)
{
return -1;
}
}
private int GetFileCount(SftpClient client, string directory)
{
List<SftpFile> files = client.ListDirectory(directory) as List<SftpFile>;
return files.Count;
}
}
}