最近有个项目需要使用sftp上传和下载文件,在.Net 中我没有找到现成的类库可用(有知道的有劳告知我,也好学习一下
),sftp我也不需要太多介绍,网上一大堆,感兴趣的可以去soso啊。
下面我简单贴出我实现的代码,防止我忘记,以后有需要,可以直接到这里Copy,haha。。。
public class sFtpHelper
{
public static int DownloadFtp(string filePath, string localPath, string fileName, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{
string localFileName = localPath + "\\" + fileName;
string remoteFileName = $"/{filePath}/{fileName}";
try
{
using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
sftp.Connect();
using (var file = File.OpenWrite(localFileName))
{
sftp.DownloadFile(remoteFileName, file);
}
sftp.Disconnect();
Log.getInstace().WriteSysInfo($"下载文件{localFileName}成功", "info");
Console.WriteLine($"下载文件成功,文件路径:{localFileName}");
return 0;
}
}
catch (Exception e)
{
Log.getInstace().WriteSysInfo($"下载文件{localFileName}失败,原因:{e}", "err");
Console.WriteLine($"下载失败,原因:{e}");
return -2;
}
}
public static int UploadFtp(string filePath, string localPath, string filename, string ftpServerIP, string ftpPort, string ftpUserID, string ftpPassword)
{
string localFileName = localPath + "\\" + filename;
string remoteFileName = $"/{filePath}/{filename}";
try
{
using (var sftp = new SftpClient(ftpServerIP, Convert.ToInt32(ftpPort), ftpUserID, ftpPassword))
{
sftp.Connect();
using (var file = File.OpenWrite(localFileName))
{
sftp.UploadFile( file,remoteFileName);
}
sftp.Disconnect();
Log.getInstace().WriteSysInfo($"上传文件{localFileName}成功", "info");
Console.WriteLine($"上传文件成功,文件路径:{localFileName}");
return 0;
}
}
catch (Exception e)
{
Log.getInstace().WriteSysInfo($"上传文件{localFileName}失败,原因:{e}", "err");
Console.WriteLine($"上传失败,原因:{e}");
return -2;
}
}
}
使用方法是在项目中引用Renci.SshNet.dll类库,类库下载地址:https://yunpan.cn/cRePDjuevZF9b 访问密码 8c5e