目录
搭建FTP服务
2.FileZilla Server搭建FTP详细教程
* 官方下载地址(里面有服务端和客户端根据需求下载)
https://www.filezilla.cn/download
* 傻瓜式安装服务器端,可以更换安装路径
* 配置服务端
服务端运行时有小窗口弹出,需要配置主机、端口、密码(根据实际情况)
本机:localhost 14147 password
esc服务器:192.168.0.1 14147 password
* 配置访问Ftp服务的用户和共享文件夹
点击菜单栏 设置 用户 或者 点击菜单栏 小人头图标
添加——>输入账户名称——>确定 ——>勾选密码——>输入密码——>点击确定
弹窗创建共享文件夹——>添加——>选择创建好的文件夹——>勾选文件夹、目录权限——>确定
* 阿里云服务器要配置安全组
比如登录FTP服务的14147一直往后延伸10个IP 14147-14157
* 服务端设置 (本地搭建的无需设置)
设置——>被动模式设置——>输入自定义端口范围 14147-14157
3..Net 4.0代码实现过程
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace SyncFileTool.Utils
{
/// <summary>
/// FTP帮助类
/// </summary>
public class FTPUtil
{
/// <summary>
/// WebClient连接FTP服务上载文件
/// </summary>
/// <param name="ftpUrl">ftp 的ip地址</param>
/// <param name="ftpUserName">访问ftp账户名</param>
/// <param name="ftpPassword">访问ftp账户密码</param>
/// <param name="fileName">ftp文件名</param>
/// <param name="localFile">本地文件(绝对路径)</param>
public static void WebClientUploadFileToFtp(string ftpUrl,string ftpUserName,string ftpPassword, string fileName, string localFile)
{
try
{
Console.WriteLine($"开始往FTP://{ftpUrl}上传{fileName}");
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
client.Encoding = System.Text.Encoding.GetEncoding("GB2312");
//上传文件
client.UploadFile($"ftp://{ftpUrl}/{fileName}", WebRequestMethods.Ftp.UploadFile, localFile);
}
Console.WriteLine($"文件:{fileName} 上传到FTP://{ftpUrl}/成功");
LogHelper.Info($"文件:{fileName} 上传到FTP://{ftpUrl}/成功");
}
catch (Exception ex)
{
LogHelper.Error($"文件:{fileName} 上传到FTP://{ftpUrl}/失败;错误信息:{ex.Message}");
}
}
/// <summary>
/// 判断Ftp上该文件是否存在
/// </summary>
/// <param name="ftpUrl">ftp 的ip地址</param>
/// <param name="ftpUserName">访问ftp账户名</param>
/// <param name="ftpPassword">访问ftp账户密码</param>
/// <param name="filePath">本地文件(绝对路径)</param>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public static bool FtpWebRequestGetFile(string ftpUrl, string ftpUserName, string ftpPassword, string filePath, string fileName)
{
Console.WriteLine($"检查文件:{fileName}是否存在");
try
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create($"ftp://{ftpUrl}/{fileName}");
ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
ftpRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse())
{
//判断ftp文件是否存在
var statusCode = ftpResponse.StatusCode;
if (statusCode == FtpStatusCode.FileStatus)
{
//获取本地文件大小跟ftp服务器文件进行对比 不一致直接覆盖
FileInfo file = new FileInfo(filePath);
if (file.Length != ftpResponse.ContentLength)
{
return false;
}
return true;
}
}
}
catch (Exception ex)
{
LogHelper.Error($"检查文件:{fileName} 时发生异常;错误信息:{ex.Message}");
}
return false;
}
}
}
搭建SFTP服务
2.通过Nuget下载SSH.Net包
3..Net4.0 代码实现
using Bingosoft.Common.AntiAttack.Xss;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SyncFileTool.Utils
{
/// <summary>
/// SFTP静态工具类
/// </summary>
public static class SftpStaticUtil
{
#region 字段或属性
private static SftpClient sftp;
/// <summary>
/// SFTP连接状态
/// </summary>
public static bool Connected { get { return sftp.IsConnected; } }
//SFTP服务器IP
private static string ip = ConfigurationManager.AppSettings["SftpIp"];
//SFTP服务器账号
private static string userName = ConfigurationManager.AppSettings["SftpUserName"];
//SFTP服务器密码
private static string cipher = ConfigurationManager.AppSettings["SftpCipher"];
//SFTP服务器端口
private static string port = ConfigurationManager.AppSettings["SftpPort"];
#endregion
#region 初始化连接
/// <summary>
/// 初始化连接
/// </summary>
static SftpStaticUtil()
{
string clearText = DesUtil.GetPassword(cipher);
sftp = new SftpClient(ip, Int32.Parse(port), userName, clearText);
Connect();
}
#endregion
#region 连接SFTP
/// <summary>
/// 连接SFTP
/// </summary>
/// <returns>true成功</returns>
public static bool Connect()
{
try
{
if (!Connected)
{
sftp.Connect();
}
return true;
}
catch (Exception ex)
{
throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message));
}
}
#endregion
#region 断开SFTP
/// <summary>
/// 断开SFTP
/// </summary>
public static void Disconnect()
{
try
{
if (sftp != null && Connected)
{
sftp.Disconnect();
}
}
catch (Exception ex)
{
throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message));
}
}
#endregion
#region SFTP上传文件
/// <summary>
/// SFTP上传文件
/// </summary>
/// <param name="localFile">本地文件全路径 例:G:\\Project\\logo.png</param>
/// <param name="remotePath">远程路径 例:/logo.png</param>
public static void Put(string localFile, string remotePath)
{
Console.WriteLine($"开始往FTP://{ip}上传{remotePath}");
try
{
using (Stream input = File.OpenRead(System.Web.HttpUtility.HtmlDecode(AntiXss.HtmlEncode(localFile)).Replace("..", "").Replace("../", "").Replace("~/", "")))
{
Connect();
sftp.UploadFile(input, remotePath);
Disconnect();
}
Console.WriteLine($"文件:{remotePath} 上传到FTP://{ip}/成功");
LogHelper.Info($"文件:{remotePath} 上传到FTP://{ip}/成功");
}
catch (Exception ex)
{
LogHelper.Error($"文件上传到sftp失败;错误信息:{ex.Message}");
}
}
#endregion
#region SFTP获取文件
/// <summary>
/// SFTP获取文件
/// </summary>
/// <param name="remotePath">远程路径</param>
/// <param name="localPath">本地路径</param>
public static void Get(string remotePath, string localPath)
{
try
{
Connect();
var byt = sftp.ReadAllBytes(remotePath);
Disconnect();
File.WriteAllBytes(localPath, byt);
}
catch (Exception ex)
{
LogHelper.Error(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
}
}
#endregion
#region SFTP判断文件是否存在
/// <summary>
/// SFTP获取文件
/// </summary>
/// <param name="remotePath">远程路径</param>
/// <param name="localFile">本地路径</param>
public static bool Exsit(string remotePath, string localFile)
{
Console.WriteLine($"检查文件:{remotePath}是否存在");
try
{
Connect();
var byt = sftp.ReadAllBytes(remotePath);
Disconnect();
FileInfo fileInfo = new FileInfo(System.Web.HttpUtility.HtmlDecode(AntiXss.HtmlEncode(localFile)).Replace("..", "").Replace("../", "").Replace("~/", ""));
if (fileInfo.Length != byt.Length)
{
return false;
}
return true;
}
catch (Exception ex)
{
if (ex.Message.Equals("Permission denied"))
{
LogHelper.Error($"远程检查文件:{remotePath}不存在,开启同步。");
}
else
{
LogHelper.Error($"检查文件:{remotePath},异常原因:{ex.Message}");
}
}
return false;
}
#endregion
#region 删除SFTP文件
/// <summary>
/// 删除SFTP文件
/// </summary>
/// <param name="remoteFile">远程路径</param>
public static void Delete(string remoteFile)
{
try
{
Connect();
sftp.Delete(remoteFile);
Disconnect();
}
catch (Exception ex)
{
LogHelper.Error(string.Format("SFTP文件删除失败,原因:{0}", ex.Message));
}
}
#endregion
}
}