大多数的SFTP服务器都是Liunx系统,此文章主要是用C#语言将文件上传到SFTP服务器,需要添加引用NuGet程序包。
1.第一步需要引入NuGet包并安装SSH.SshNet
2.引用using Renci.SshNet ,具体实现代码如下
const int port = 22; //端口
const string host = "100.121.192.66"; //sftp地址
const string username = "root"; //用户名
const string password = "XXXXXX";//密码
const string workingdirectory = "/emeeting/";//读取、上传文件的目录 "/"为根目录
const string uploadfile = @"D:\测试截图\待办.png"; //上传文件地址
/// <summary>
/// 上传文件到SFTP
/// </summary>
/// <param name="FilePath">本地文件路径 @"D:\测试截图\待办.png</param>
/// <param name="WorkDirectory">上传到工作目录 /emeeting/</param>
/// <returns>上传结果</returns>
public bool UploadSftpFile(string FilePath, string WorkDirectory)
{
bool flag = false;
// 文件名称
string fileName = FilePath.Substring(FilePath.LastIndexOf('\\')+1);
try
{
using (var client = new SftpClient(host, port, username, password)) //创建连接对象
{
client.Connect(); //连接
client.ChangeDirectory(WorkDirectory); //切换目录
List<string> fileNameList = new List<string>();
using (var fileStream = new FileStream(FilePath, FileMode.Open))
{
client.BufferSize = 4 * 1024;
if (client.Exists(WorkDirectory + fileName))
{
client.DeleteFile(fileName);
}
client.UploadFile(fileStream, Path.GetFileName(FilePath));
var listDirectory = client.ListDirectory(WorkDirectory); //获取目录下所有文件
foreach (var fi in listDirectory) //遍历文件
{
fileNameList.Add(fi.Name);
}
// "待办.png"
if (fileNameList.Contains(fileName))
flag = true;
}
}
}
catch (Exception ex)
{
throw ex;
}
return flag;
}
/// <summary>
/// 删除SFTP服务器的文件
/// </summary>
/// <param name="filePath">SFTP文件路径 /emeeting/待办.png</param>
/// <returns>是否删除成功</returns>
public bool DeleteSFtpFile(string filePath)
{
bool flag = false;
string workdir = filePath.Substring(0,filePath.LastIndexOf('/')+1);
string fileName= filePath.Substring(filePath.LastIndexOf('/') + 1);
try
{
List<string> fileNameList = new List<string>();
using (var client = new SftpClient(host, port, username, password)) //创建连接对象
{
client.Connect(); //连接
client.ChangeDirectory(workdir); //切换目录
//var listDirectory = client.ListDirectory(workdir); //获取目录下所有文件
//foreach (var fi in listDirectory) //遍历文件
//{
// if (fi.Name==fileName)
// fi.Delete();
//}
if (client.Exists(fileName))
{
client.DeleteFile(fileName);
}
else
{
MessageBox.Show("不存在该文件");
}
var listDirectory = client.ListDirectory(workdir); //获取目录下所有文件
foreach (var fi in listDirectory) //遍历文件
{
fileNameList.Add(fi.Name);
}
if (!fileNameList.Contains(fileName))
flag = true;
else
flag = false;
}
}
catch (Exception ex)
{
throw ex;
}
return flag;
}
该文章引用了此网站,并做了一些修改,欢迎各位指点https://www.cnblogs.com/jrsnd/p/3813387.html