通常在做服务器与服务器文件、服务器与本地文件同步时通过Ftp服务实现,下面就以服务器文件和本地同步为例,介绍一下Ftp同步文件:
首先建立一个Ftp站点服务,基本身份验证登陆,端口号为默认的21;
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实现文件同步的更多相关文章

  1. sftp ftp文件同步方案

    sftp ftp文件同步方案 1. 需求 1.1实现网关服务器的ftp服务器的/batchFileRequest目录下文件向徽商所使用的sftp服务器的/batchFileRequest目录同步文件 ...

  2. 烂泥:linux文件同步之rsync学习(一)

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 这几天刚好有空就打算开始学习linux下的文件同步软件rsync,在学习rsync时,我们可以分以下几个步骤进行: 1. rsync是什么 2. rsy ...

  3. Rsync 3.1.0 发布,文件同步工具

    文件同步工具Rsync 3.1.0发布.2013-09-29 上一个版本还是2011-09-23的3.0.9 过了2年多.Rsync基本是Linux上文件同步的标准了,也可以和inotify配合做实时 ...

  4. ftp (文件传输协议)

    ftp (文件传输协议) 锁定 本词条由“科普中国”百科科学词条编写与应用工作项目 审核 . FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议” ...

  5. Linux下利用rsync实现多服务器文件同步

    windows做为文件服务器,使用rsync的windows服务版本,然后配置好就可以了.需要的朋友可以参考下. windows做为文件服务器,使用rsync的windows服务版本:cwRsyncS ...

  6. Windows Server 2008文件同步

    配置Windows Server 2008文件同步   摘要: 众所周知,Linux系统可以用rsync来实现文件或目录的同步,windows系统下也一样可以.我们现在就用cwRsync来实现wind ...

  7. rsync 文件同步和备份

    rsync 是同步文件的利器,一般用于多个机器之间的文件同步与备份,同时也支持在本地的不同目录之间互相同步文件.在这种场景下,rsync 远比 cp 命令和 ftp 命令更加合适,它只会同步需要更新的 ...

  8. CentOS安装和配置Rsync进行文件同步

    Liunx系统实现文件同步不需要搭建FTP这类的工具,只需要按照Rsync配置下文件就可以. 本文以Centos7.0为例. 1. 首先关闭SELINUX(不关闭无法同步,权限太高了) vi /etc ...

  9. Rsync文件同步工具

    前段时间因公司需求,需要把备份的文件进行同步保存,后面就想到了我们大家都最熟悉的文件同步工作Rsync,于是就捣鼓了一下午时间,然后总结了下大概过程和参数详情. 首先了解了下rsync同步的大致原理: ...

随机推荐

  1. iOS 网络与多线程--8.百度地图的使用(调用系统浏览器)

    通过调用设备自带的浏览器,打开百度地图 // 1.定义一个方法,用来打开谷歌地图的功能 -(IBAction)openMaps { // 2.定义一个字符串,作为百度地图的当前地理位置 废弃 NSSt ...

  2. myql查询创建表语句SHOW CREATE TABLE table_name

    技术背景:刚开始学习MySQL时候,有时偷懒,会用SHOW CREATE TABLE 表名\G来复制表创建语句,可是当运行的时候总会因为"表名和列名上有单引号",提示语法错误不能运 ...

  3. 武汉科技大学ACM:1005: Soapbear and Honey

    Problem Description Soapbear is the mascot of WHUACM team. Like other bears, Soapbear loves honey ve ...

  4. python简介与基本操作

    一.python的历史 python的创始人Guido van Rossum,现就职于Dropbox公司. 1989年12月份诞生了python1.0 2000年10月16日发布了python2.0 ...

  5. 【持久化框架】Mybatis与Hibernate的详细对比

        前言 这篇博文我们重点分析一下Mybatis与hibernate的区别,当然在前面的博文中我们已经深入的研究了Mybatis和Hibernate的原理. Mybatis [持久化框架]Myba ...

  6. windows 2003 远程桌面 连接输入账号密码后,只能看见蓝色屏幕和鼠标

    具体解决方案参考的 http://www.tomshardware.com/forum/171045-46-remote-desktop-connection-blank-desktop   to s ...

  7. c#使用spy进行模拟操作

    很无奈,写了很长时间,最后保存时网页失去响应,真是要命呢.本来想就此放弃了,但是想还是粗略的重写一次吧,希望日后可以对朋友有一定的帮助. Microsoft.Spy工具是一个基础工具,我们简要介绍一下 ...

  8. C# and android

    http://www.cnblogs.com/GoodHelper/archive/2011/07/08/android_socket_chart.html http://blog.csdn.net/ ...

  9. ASP.NET 表单认证与角色授权

    参考 : http://hi.baidu.com/iykqqlpugocfnqe/item/e132329bdea22acbb6253105  ASP.NET中处理请求的流程图 http://www. ...

  10. Linux下的QQ折腾记

        用Linux最重要是要把QQ装好了,webqq很不好用.qq for linux是古董,Linux还是悲惨,很多软件有windows版本,有mac版本,就是不出linux版本.只好用wine来 ...