Ftp实现文件同步

时间:2022-11-29 01:06:20

通常在做服务器与服务器文件、服务器与本地文件同步时通过Ftp服务实现,下面就以服务器文件和本地同步为例,介绍一下Ftp同步文件:
首先建立一个Ftp站点服务,基本身份验证登陆,端口号为默认的21;
Ftp文件同步前端界面如下:

Ftp实现文件同步

Ftp文件同步后台实现

 #region 获取Ftp服务端文件比较替换
/// <summary>
/// 比较替换
/// </summary>
private void btnQuery_Click(object sender, EventArgs e)
{
msg.AppendText(Environment.NewLine + "开始连接...");
FtpHelp fw = new FtpHelp(service.Text.Trim(), "", lognName.Text.Trim(), Pwd.Text.Trim());
if (fw.ISOK())
{
msg.AppendText(Environment.NewLine + "连接成功!\r\n");
Replace(service.Text.Trim(), hostAdress.Text.Trim());
}
else
{
msg.AppendText(Environment.NewLine + "连接失败!\r\n");
}
}
private bool _isOver = false;
private void Replace(string ftpAdress, string hostAdress)
{
if (!_isOver)
{
_isOver = true;
//链接ftp服务
FtpHelp ftphelp = new FtpHelp(service.Text.Trim(), "", lognName.Text.Trim(), Pwd.Text.Trim());
//获取本地文件
LogHostFile[] hostFile = GetFile(hostAdress);
LogWriter.LogInfo("获取本地文件完成共:" + hostFile.Count());
//获取FTP服务器文件
DateTime begin = DateTime.Now;
FtpFile[] files = ftphelp.GetFilesList("ftp://" + ftpAdress.Trim(), "");
DateTime end = DateTime.Now;
time.Text = "获取服务文件用时:" + (end - begin).Milliseconds.ToString() + "ms;共" + files.Count() + "个文件";
if (files.Count() == )
{
LogWriter.LogInfo("获取服务器文件完成共:" + files.Count() + "可能是服务器连接失败或真的没有文件请管理员查看");
}
else
{
LogWriter.LogInfo("获取服务器文件完成共:" + files.Count());
}
Dictionary host = new Dictionary();
Dictionary ftp = new Dictionary();
if (hostAdress == "")
{
LogWriter.LogError("本地路径为空");
}
else
{
try
{
//遍历Ftp服务器端的文件
ftp.Clear();
foreach (FtpFile ftpfile in files)
{
if (!ftp.ContainsKey(ftpfile.FileFullName))
{
ftp.Add(ftpfile.FileFullName, ftpfile.FileSize);
}
}
//遍历本地服务器端的文件
host.Clear();
foreach (LogHostFile ftpfile in hostFile)
{
if (!host.ContainsKey(ftpfile.FileFullName))
{
host.Add(ftpfile.FileFullName, ftpfile.FileSize);
}
}
}
catch (Exception ex)
{
LogWriter.LogError("将本地和服务文件放入Dictionary集合中出错:" + ex.Message);
}
finally
{
_isOver = false;
}
LogWriter.LogInfo("开始循环服务器中的文件比较替换");
bool IsRelpace = false;
foreach (KeyValuePair ftpfile in ftp)
{
#region 判断服务器端的文件是否在本地存在
//判断服务器端的文件是否在本地存在
if (host.Count != )//如果本地没有文件
{
#region 是否有这个文件
if (host.ContainsKey(ftpfile.Key))
{
#region 如果存在判断两个文件的大小是否相等
//如果存在判断两个文件的大小是否相等
if (host[ftpfile.Key] != ftpfile.Value)
{
IsRelpace = true;
LogWriter.LogInfo(ftpfile.Key + " 文件在本地的大小:" + host[ftpfile.Key] + ";在服务器的大小:" + ftpfile.Value);
//不相等就等换
try
{
if (ftphelp.Download(hostAdress, ftpfile.Key.Trim()))
{
msg.AppendText(Environment.NewLine + "开始替换" + "ftp://" + ftpAdress.Trim() + "/" + ftpfile.Key + "\r\n");
msg.AppendText(Environment.NewLine + "替换中..." + "\r\n");
msg.AppendText(Environment.NewLine + "替换成功!" + "\r\n");
LogWriter.LogInfo("替换文件:" + ftpfile.Key.Trim() + "本地文件大小:" + host[ftpfile.Key] + "; FTP文件大小:" + ftpfile.Value);
}
else
{
msg.AppendText(Environment.NewLine + "替换失败!" + "\r\n");
LogWriter.LogError("替换文件:" + ftpfile.Key.Trim() + "失败");
}
}
catch (Exception ex)
{
LogWriter.LogError("文件" + ftpfile.Key + "比较替换时失败:" + ex.Message);
}
finally
{
_isOver = false;
}
}
#endregion
}
else
{
IsRelpace = true;
try
{
if (ftphelp.Download(hostAdress, ftpfile.Key.Trim()))
{
msg.AppendText(Environment.NewLine + "本地没有的文件开始下载" + "ftp://" + ftpAdress.Trim() + "/" + ftpfile.Key);
msg.AppendText(Environment.NewLine + "下载中...");
msg.AppendText(Environment.NewLine + "下载成功!");
LogWriter.LogInfo("下载服务器文件" + ftpfile.Key.Trim());
}
else
{
msg.AppendText(Environment.NewLine + "下载新文件失败!");
LogWriter.LogError("下载服务器文件" + ftpfile.Key.Trim() + "失败");
}
}
catch (Exception ex)
{
LogWriter.LogError("文件" + ftpfile.Key + "下载时失败:" + ex.Message);
}
finally
{
_isOver = false;
}
}
#endregion
}
else
{
IsRelpace = true;
try
{
if (ftphelp.Download(hostAdress, ftpfile.Key.Trim()))
{
msg.AppendText(Environment.NewLine + "本地没有的文件开始下载" + "ftp://" + ftpAdress.Trim() + "/" + ftpfile.Key);
msg.AppendText(Environment.NewLine + "下载中...");
msg.AppendText(Environment.NewLine + "下载成功!");
LogWriter.LogInfo("下载服务器文件" + ftpfile.Key.Trim());
}
else
{
msg.AppendText(Environment.NewLine + "下载新文件失败!");
LogWriter.LogError("下载服务器文件" + ftpfile.Key.Trim() + "失败");
}
}
catch (Exception ex)
{
LogWriter.LogError("文件" + ftpfile.Key + "下载时失败:" + ex.Message);
}
finally
{
_isOver = false;
}
}
#endregion
}
if (IsRelpace)
{
LogWriter.LogInfo("替换工作完成!!");
}
else
{
LogWriter.LogInfo("FTP和本地的文件没有不同不需要替换");
}
}
}
else
{
LogWriter.LogInfo("上一次替换未执行完成不进行下一次的操作!");
}
}
#endregion
#region 获取本地文件
public LogHostFile[] GetFile(string str)
{
List hostFile = new List();
if (str != "")
{
string filepath = hostAdress.Text.Trim();
DirectoryInfo theFolder = new DirectoryInfo(str);
//LogWriter.LogInfo(str);
FileSystemInfo[] fileinfo = theFolder.GetFileSystemInfos();
foreach (FileSystemInfo NextFolder in fileinfo)
{
if (this.GetFileType(NextFolder.FullName) == )//wenjian
{
FileInfo Next = (FileInfo)NextFolder;
long size = Next.Length;
//获取文件的名称
hostFile.Add(new LogHostFile() { FileSize = size, FileFullName = NextFolder.FullName.Replace("\\", "/").Remove(, filepath.Length).Substring() });
LogWriter.LogInfo(NextFolder.FullName);
}
else if (this.GetFileType(NextFolder.FullName) == )//wenjianjia
{
LogHostFile[] hostfile = GetFile(NextFolder.FullName);
foreach (LogHostFile file in hostfile)
{
hostFile.Add(file);
}
}
}
}
else
{
LogWriter.LogError("没有给本地文件路径!");
}
return hostFile.ToArray();
}
#endregion
/// <summary>
/// 判断是文件还是文件夹
/// </summary>
public int GetFileType(string path)
{
if (File.Exists(path))
{
return ;
// 是文件
}
else if (Directory.Exists(path))
{
return ;
// 是文件夹
}
else
{
return ;
// 都不是
}
}

Ftp操作帮助类

 public class FtpHelp
{
string ftpServerIP;
string ftpRemotePath;
string ftpUserName;
string ftpPassword;
string ftpURI;
#region 连接FTP
/// <summary>
/// 连接FTP
/// </summary>
/// FTP连接地址
/// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录
/// 用户名
/// 密码
public FtpHelp(string FtpServerIP, string FtpRemotePath, string FtpUserName, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserName = FtpUserName;
ftpPassword = FtpPassword;
ftpURI = "ftp://" + ftpServerIP + "/";
}
/// <summary>
/// 是否连接成功
/// </summary>
public bool ISOK()
{
try
{
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
return true;
}catch(Exception e)
{
return false;
}
}
#endregion
#region 下载
/// <summary>
/// 下载
/// </summary>
public bool Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
string newpath="";
if (fileName.Contains("/"))
{
newpath=fileName.Substring(,fileName.LastIndexOf(@"/"));
newpath = newpath.Replace("/", "\\");
}
string path = filePath+"\\" + newpath;
DirectoryInfo di = new DirectoryInfo(path);
if (!di.Exists)
{
di.Create();
}
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = ;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, , bufferSize);
while (readCount &gt; )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return true;
}
catch (Exception ex)
{
LogWriter.LogError("文件" + fileName + "下载失败:" + ex.Message);
// Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --&gt; " + ex.Message);
return false;
}
}
#endregion
#region 获取当前目录下明细(包含文件和文件夹)
string name = "";
public FtpFile[] GetFilesList(string ftpURI,string name)
{
List result = new List();
try
{
FtpWebRequest ftp;
Uri uri = new Uri(ftpURI);
LogWriter.LogInfo(uri.Host);
LogWriter.LogInfo(uri.HostNameType.ToString());
LogWriter.LogInfo(uri.IsFile.ToString());
LogWriter.LogInfo(uri.LocalPath);
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
ftp.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftp.Timeout = ;
string aa = "";
using (WebResponse response = ftp.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.ASCIIEncoding.UTF8))
{
aa = reader.ReadToEnd();
reader.Close();
response.Close();
}
}
string[] ftpFileList = aa.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach(string line in ftpFileList)
{
if (line.Contains(""))
{
string dirName = GetFileName(line);
string newUrl = ftpURI + @"/" + dirName;
string newName = name + @"/" + dirName;
FtpFile[] files = GetFilesList(newUrl, newName);
foreach (FtpFile file in files)
{
result.Add(file);
}
}
else
{
string fileName = GetFileName(line);
string[] ftpFile = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
//获取文件的大小 和全路径
result.Add(new FtpFile() { FileSize = int.Parse(ftpFile[]), FileFullName = (name + @"/" + fileName).Substring() });
}
}
}
catch (Exception ex)
{
string message = ex.Message;
// Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --&gt; " + ex.Message);
LogWriter.LogError(ex.Message);
}
return result.ToArray();
}
private string GetFileName(string line)
{
string newStr = line.Substring(line.IndexOf(" "));
newStr = newStr.TrimStart();
newStr = newStr.Substring(newStr.IndexOf(" "));
newStr = newStr.TrimStart();
newStr = newStr.Substring(newStr.IndexOf(" "));
return newStr.Trim();
}
/// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
public string[] GetFilesDetailList()
{
string[] downloadFiles;
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
ftp.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
//string aa = reader.ReadToEnd();
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("\n"), );
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
string message = ex.Message;
// Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --&gt; " + ex.Message);
return downloadFiles;
}
}
#endregion
}

Ftp文件同步工具最终效果

Ftp实现文件同步