码迷,mamicode.com
首页 > 其他好文 > 详细

Ftp实现文件同步

时间:2015-11-23 18:56:57      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享

Ftp文件同步后台实现

技术分享
  1 #region 获取Ftp服务端文件比较替换
  2         /// <summary>
  3         /// 比较替换
  4         /// </summary>
  5         private void btnQuery_Click(object sender, EventArgs e)
  6         {           
  7             msg.AppendText(Environment.NewLine + "开始连接...");
  8             FtpHelp fw = new FtpHelp(service.Text.Trim(), "", lognName.Text.Trim(), Pwd.Text.Trim());
  9             if (fw.ISOK())
 10             {
 11                 msg.AppendText(Environment.NewLine + "连接成功!\r\n");
 12                 Replace(service.Text.Trim(), hostAdress.Text.Trim());
 13             }
 14             else
 15             {
 16                 msg.AppendText(Environment.NewLine + "连接失败!\r\n");
 17             }      
 18         }
 19         private bool _isOver = false;
 20         private void Replace(string ftpAdress, string hostAdress)
 21         {
 22             if (!_isOver)
 23             {
 24                 _isOver = true;
 25                 //链接ftp服务
 26                 FtpHelp ftphelp = new FtpHelp(service.Text.Trim(), "", lognName.Text.Trim(), Pwd.Text.Trim());
 27                 //获取本地文件
 28                 LogHostFile[] hostFile = GetFile(hostAdress);
 29                 LogWriter.LogInfo("获取本地文件完成共:" + hostFile.Count());
 30                 //获取FTP服务器文件
 31                 DateTime begin = DateTime.Now;
 32                 FtpFile[] files = ftphelp.GetFilesList("ftp://" + ftpAdress.Trim(), "");
 33                 DateTime end = DateTime.Now;
 34                 time.Text = "获取服务文件用时:" + (end - begin).Milliseconds.ToString() + "ms;共" + files.Count() + "个文件";
 35                 if (files.Count() == 0)
 36                 {
 37                     LogWriter.LogInfo("获取服务器文件完成共:" + files.Count() + "可能是服务器连接失败或真的没有文件请管理员查看");
 38                 }
 39                 else
 40                 {
 41                     LogWriter.LogInfo("获取服务器文件完成共:" + files.Count());
 42                 }
 43                 Dictionary host = new Dictionary();
 44                 Dictionary ftp = new Dictionary();
 45                 if (hostAdress == "")
 46                 {
 47                     LogWriter.LogError("本地路径为空");
 48                 }
 49                 else
 50                 {
 51                     try
 52                     {
 53                         //遍历Ftp服务器端的文件
 54                         ftp.Clear();
 55                         foreach (FtpFile ftpfile in files)
 56                         {
 57                             if (!ftp.ContainsKey(ftpfile.FileFullName))
 58                             {
 59                                 ftp.Add(ftpfile.FileFullName, ftpfile.FileSize);
 60                             }
 61                         }
 62                         //遍历本地服务器端的文件
 63                         host.Clear();
 64                         foreach (LogHostFile ftpfile in hostFile)
 65                         {
 66                             if (!host.ContainsKey(ftpfile.FileFullName))
 67                             {
 68                                 host.Add(ftpfile.FileFullName, ftpfile.FileSize);
 69                             }
 70                         }
 71                     }
 72                     catch (Exception ex)
 73                     {
 74                         LogWriter.LogError("将本地和服务文件放入Dictionary集合中出错:" + ex.Message);
 75                     }
 76                     finally
 77                     {
 78                         _isOver = false;
 79                     }
 80                     LogWriter.LogInfo("开始循环服务器中的文件比较替换");
 81                     bool IsRelpace = false;
 82                     foreach (KeyValuePair ftpfile in ftp)
 83                     {
 84                         #region 判断服务器端的文件是否在本地存在
 85                         //判断服务器端的文件是否在本地存在
 86                         if (host.Count != 0)//如果本地没有文件
 87                         {
 88                             #region 是否有这个文件
 89                             if (host.ContainsKey(ftpfile.Key))
 90                             {
 91                                 #region 如果存在判断两个文件的大小是否相等
 92                                 //如果存在判断两个文件的大小是否相等
 93                                 if (host[ftpfile.Key] != ftpfile.Value)
 94                                 {
 95                                     IsRelpace = true;
 96                                     LogWriter.LogInfo(ftpfile.Key + " 文件在本地的大小:" + host[ftpfile.Key] + ";在服务器的大小:" + ftpfile.Value);
 97                                     //不相等就等换
 98                                     try
 99                                     {
100                                         if (ftphelp.Download(hostAdress, ftpfile.Key.Trim()))
101                                         {
102                                             msg.AppendText(Environment.NewLine + "开始替换" + "ftp://" + ftpAdress.Trim() + "/" + ftpfile.Key + "\r\n");
103                                             msg.AppendText(Environment.NewLine + "替换中..." + "\r\n");
104                                             msg.AppendText(Environment.NewLine + "替换成功!" + "\r\n");
105                                             LogWriter.LogInfo("替换文件:" + ftpfile.Key.Trim() + "本地文件大小:" + host[ftpfile.Key] + ";   FTP文件大小:" + ftpfile.Value);
106                                         }
107                                         else
108                                         {
109                                             msg.AppendText(Environment.NewLine + "替换失败!" + "\r\n");
110                                             LogWriter.LogError("替换文件:" + ftpfile.Key.Trim() + "失败");
111                                         }
112                                     }
113                                     catch (Exception ex)
114                                     {
115                                         LogWriter.LogError("文件" + ftpfile.Key + "比较替换时失败:" + ex.Message);
116                                     }
117                                     finally
118                                     {
119                                         _isOver = false;
120                                     }
121                                 }
122                                 #endregion
123                             }
124                             else
125                             {
126                                 IsRelpace = true;
127                                 try
128                                 {
129                                     if (ftphelp.Download(hostAdress, ftpfile.Key.Trim()))
130                                     {
131                                         msg.AppendText(Environment.NewLine + "本地没有的文件开始下载" + "ftp://" + ftpAdress.Trim() + "/" + ftpfile.Key);
132                                         msg.AppendText(Environment.NewLine + "下载中...");
133                                         msg.AppendText(Environment.NewLine + "下载成功!");
134                                         LogWriter.LogInfo("下载服务器文件" + ftpfile.Key.Trim());
135                                     }
136                                     else
137                                     {
138                                         msg.AppendText(Environment.NewLine + "下载新文件失败!");
139                                         LogWriter.LogError("下载服务器文件" + ftpfile.Key.Trim() + "失败");
140                                     }
141                                 }
142                                 catch (Exception ex)
143                                 {
144                                     LogWriter.LogError("文件" + ftpfile.Key + "下载时失败:" + ex.Message);
145                                 }
146                                 finally
147                                 {
148                                     _isOver = false;
149                                 }
150                             }
151                             #endregion
152                         }
153                         else
154                         {
155                             IsRelpace = true;
156                             try
157                             {
158                                 if (ftphelp.Download(hostAdress, ftpfile.Key.Trim()))
159                                 {
160                                     msg.AppendText(Environment.NewLine + "本地没有的文件开始下载" + "ftp://" + ftpAdress.Trim() + "/" + ftpfile.Key);
161                                     msg.AppendText(Environment.NewLine + "下载中...");
162                                     msg.AppendText(Environment.NewLine + "下载成功!");
163                                     LogWriter.LogInfo("下载服务器文件" + ftpfile.Key.Trim());
164                                 }
165                                 else
166                                 {
167                                     msg.AppendText(Environment.NewLine + "下载新文件失败!");
168                                     LogWriter.LogError("下载服务器文件" + ftpfile.Key.Trim() + "失败");
169                                 }
170                             }
171                             catch (Exception ex)
172                             {
173                                 LogWriter.LogError("文件" + ftpfile.Key + "下载时失败:" + ex.Message);
174                             }
175                             finally
176                             {
177                                 _isOver = false;
178                             }
179                         }
180                         #endregion
181                     }
182                     if (IsRelpace)
183                     {
184                         LogWriter.LogInfo("替换工作完成!!");
185                     }
186                     else
187                     {
188                         LogWriter.LogInfo("FTP和本地的文件没有不同不需要替换");
189                     }
190                 }
191             }
192             else
193             {
194                 LogWriter.LogInfo("上一次替换未执行完成不进行下一次的操作!");
195             }
196         }
197         #endregion
198         #region 获取本地文件
199         public LogHostFile[] GetFile(string str)
200         {
201             List hostFile = new List();
202             if (str != "")
203             {
204                 string filepath = hostAdress.Text.Trim();
205                 DirectoryInfo theFolder = new DirectoryInfo(str);
206                 //LogWriter.LogInfo(str);
207                 FileSystemInfo[] fileinfo = theFolder.GetFileSystemInfos();
208                 foreach (FileSystemInfo NextFolder in fileinfo)
209                 {
210                     if (this.GetFileType(NextFolder.FullName) == 0)//wenjian
211                     {
212                         FileInfo Next = (FileInfo)NextFolder;
213                         long size = Next.Length;
214                         //获取文件的名称
215                         hostFile.Add(new LogHostFile() { FileSize = size, FileFullName = NextFolder.FullName.Replace("\\", "/").Remove(0, filepath.Length).Substring(1) });
216                         LogWriter.LogInfo(NextFolder.FullName);
217                     }
218                     else if (this.GetFileType(NextFolder.FullName) == 1)//wenjianjia
219                     {
220                         LogHostFile[] hostfile = GetFile(NextFolder.FullName);
221                         foreach (LogHostFile file in hostfile)
222                         {
223                             hostFile.Add(file);
224                         }
225                     }
226                 }
227             }
228             else
229             {
230                 LogWriter.LogError("没有给本地文件路径!");
231             }
232             return hostFile.ToArray();
233         }
234         #endregion
235         /// <summary>
236         /// 判断是文件还是文件夹
237         /// </summary>
238         public int GetFileType(string path)
239         {
240             if (File.Exists(path))
241             {
242                 return 0;
243                 // 是文件
244             }
245             else if (Directory.Exists(path))
246             {
247                 return 1;
248                 // 是文件夹
249             }
250             else
251             {
252                 return 2;
253                 // 都不是
254             }
255         }
View Code

Ftp操作帮助类

技术分享
  1 public class FtpHelp
  2     {
  3         string ftpServerIP;
  4         string ftpRemotePath;
  5         string ftpUserName;
  6         string ftpPassword;
  7         string ftpURI;
  8         #region 连接FTP
  9         /// <summary>
 10         /// 连接FTP
 11         /// </summary>
 12         /// FTP连接地址
 13         /// 指定FTP连接成功后的当前目录, 如果不指定即默认为根目录
 14         /// 用户名
 15         /// 密码
 16         public FtpHelp(string FtpServerIP, string FtpRemotePath, string FtpUserName, string FtpPassword)
 17         {
 18             ftpServerIP = FtpServerIP;
 19             ftpRemotePath = FtpRemotePath;
 20             ftpUserName = FtpUserName;
 21             ftpPassword = FtpPassword;
 22             ftpURI = "ftp://" + ftpServerIP + "/";
 23         }
 24         /// <summary>
 25         /// 是否连接成功
 26         /// </summary>
 27         public bool ISOK()
 28         {
 29             try
 30             {
 31                 FtpWebRequest reqFTP;
 32                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
 33                 reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
 34                 return true;
 35             }catch(Exception e)
 36             {
 37                 return false;
 38             }           
 39          }
 40         #endregion
 41         #region  下载
 42         /// <summary>
 43         /// 下载
 44         /// </summary>
 45         public bool Download(string filePath, string fileName)
 46         {
 47             FtpWebRequest reqFTP;
 48             try
 49             {
 50                 string newpath="";
 51                 if (fileName.Contains("/"))
 52                 {
 53                     newpath=fileName.Substring(0,fileName.LastIndexOf(@"/"));
 54                     newpath = newpath.Replace("/", "\\");
 55                 }
 56                 string path = filePath+"\\" + newpath;
 57                 DirectoryInfo di = new DirectoryInfo(path);
 58                 if (!di.Exists)
 59                 {
 60                     di.Create();
 61                 }
 62                 FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
 63                 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
 64                 reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
 65                 reqFTP.UseBinary = true;
 66                 reqFTP.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
 67                 FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
 68                 Stream ftpStream = response.GetResponseStream();
 69                 long cl = response.ContentLength;
 70                 int bufferSize = 2048;
 71                 int readCount;
 72                 byte[] buffer = new byte[bufferSize];
 73                 readCount = ftpStream.Read(buffer, 0, bufferSize);
 74                 while (readCount &gt; 0)
 75                 {
 76                     outputStream.Write(buffer, 0, readCount);
 77                     readCount = ftpStream.Read(buffer, 0, bufferSize);
 78                 }
 79                 ftpStream.Close();
 80                 outputStream.Close();
 81                 response.Close();
 82                 return true;
 83             }
 84             catch (Exception ex)
 85             {
 86                 LogWriter.LogError("文件" + fileName + "下载失败:" + ex.Message);
 87                 // Insert_Standard_ErrorLog.Insert("FtpWeb", "Download Error --&gt; " + ex.Message);
 88                 return false;
 89             }
 90         }
 91         #endregion
 92         #region 获取当前目录下明细(包含文件和文件夹)
 93         string name = "";
 94         public FtpFile[] GetFilesList(string ftpURI,string name)
 95         {
 96             List result = new List();           
 97             try
 98             {
 99                 FtpWebRequest ftp;
100                 Uri uri = new Uri(ftpURI);
101                 LogWriter.LogInfo(uri.Host);
102                 LogWriter.LogInfo(uri.HostNameType.ToString());
103                 LogWriter.LogInfo(uri.IsFile.ToString());
104                 LogWriter.LogInfo(uri.LocalPath);
105                 ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
106                 ftp.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
107                 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
108                 ftp.Timeout = 10000;
109                 string aa = "";
110                 using (WebResponse response = ftp.GetResponse())
111                 {
112                     using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.ASCIIEncoding.UTF8))
113                     {
114                         aa = reader.ReadToEnd();
115                         reader.Close();
116                         response.Close();
117                     }
118                 }
119                 string[] ftpFileList = aa.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
120                 foreach(string line in ftpFileList)
121                 {
122                     if (line.Contains(""))
123                     {
124                         string dirName = GetFileName(line);
125                         string newUrl = ftpURI + @"/" + dirName;
126                         string newName = name + @"/" + dirName;
127                         FtpFile[] files = GetFilesList(newUrl, newName);
128                         foreach (FtpFile file in files)
129                         {
130                             result.Add(file);
131                         }
132                     }
133                     else
134                     {
135                         string fileName = GetFileName(line);
136                         string[] ftpFile = line.Split(new char[] {   }, StringSplitOptions.RemoveEmptyEntries);
137                         //获取文件的大小 和全路径
138                         result.Add(new FtpFile() { FileSize = int.Parse(ftpFile[2]), FileFullName = (name + @"/" + fileName).Substring(1) });
139                     }
140                 }                                
141             }
142             catch (Exception ex)
143             {                
144                 string message = ex.Message;
145                 // Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --&gt; " + ex.Message);
146                 LogWriter.LogError(ex.Message);              
147             }
148             return result.ToArray();
149         }
150         private string GetFileName(string line)
151         {
152             string newStr = line.Substring(line.IndexOf(" "));
153             newStr = newStr.TrimStart();
154             newStr = newStr.Substring(newStr.IndexOf(" "));            
155             newStr = newStr.TrimStart();
156             newStr = newStr.Substring(newStr.IndexOf(" "));          
157             return newStr.Trim();
158         }        
159         /// <summary>
160         /// 获取当前目录下明细(包含文件和文件夹)
161         /// </summary>
162         public string[] GetFilesDetailList()
163         {
164             string[] downloadFiles;
165             try
166             {
167                 StringBuilder result = new StringBuilder();
168                 FtpWebRequest ftp;
169                 ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
170                 ftp.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
171                 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
172                 WebResponse response = ftp.GetResponse();
173                 StreamReader reader = new StreamReader(response.GetResponseStream());
174                 //string aa = reader.ReadToEnd();
175                 string line = reader.ReadLine();
176                 while (line != null)
177                 {
178                     result.Append(line);
179                     result.Append("\n");
180                     line = reader.ReadLine();
181                 }
182                 result.Remove(result.ToString().LastIndexOf("\n"), 1);
183                 reader.Close();
184                 response.Close();
185                 return result.ToString().Split(\n);
186             }
187             catch (Exception ex)
188             {
189                 downloadFiles = null;
190                 string message = ex.Message;
191                 // Insert_Standard_ErrorLog.Insert("FtpWeb", "GetFilesDetailList Error --&gt; " + ex.Message);
192                 return downloadFiles;
193             }
194         }
195         #endregion
196     }
View Code

Ftp文件同步工具最终效果

技术分享

Ftp实现文件同步

标签:

原文地址:http://www.cnblogs.com/huhangfei/p/4989176.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!