1. using FtpLib;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.ServiceProcess;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13.  
  14. namespace WindowsService1
  15. {
  16. public partial class Service1 : ServiceBase
  17. {
  18. private int TimeoutMillis = ; //定时器触发间隔
  19. private int _countFileChangeEvent = , _countTimerEvent = ;
  20. System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher();
  21. System.Threading.Timer m_timer = null;
  22. System.Threading.Timer m_timerDownLoad = null;
  23. List<String> files = new List<string>(); //记录待处理文件的队列
  24.  
  25. private Thread ThreadHello;
  26. private Thread ThreadDownLoad;
  27. private List<ChannelTvListInfo> lstNewTvInfo;
  28.  
  29. public Service1()
  30. {
  31. InitializeComponent();
  32. }
  33. //http://blog.csdn.net/hwt0101/article/details/8514291
  34. //http://www.cnblogs.com/mywebname/articles/1244745.html
  35. //http://www.cnblogs.com/jzywh/archive/2008/07/23/filesystemwatcher.html
  36. /// <summary>
  37. /// 服务启动的操作
  38. /// </summary>
  39. /// <param name="args"></param>
  40. protected override void OnStart(string[] args)
  41. {
  42. try
  43. {
  44. ThreadDownLoad = new Thread(new ThreadStart(ThreadTime));
  45. ThreadDownLoad.Start();
  46. ThreadHello = new Thread(new ThreadStart(Hello));
  47. ThreadHello.Start();
  48. WriteInLog("服务线程任务开始", false);
  49. System.Diagnostics.Trace.Write("线程任务开始");
  50.  
  51. }
  52. catch (Exception ex)
  53. {
  54. System.Diagnostics.Trace.Write(ex.Message);
  55. throw ex;
  56. }
  57. }
  58. public List<ChannelTvListInfo> listFTPFiles(string FTPAddress, string username, string password)
  59. {
  60. List<ChannelTvListInfo> listinfo = new List<ChannelTvListInfo>();
  61. using (FtpConnection ftp = new FtpConnection(FTPAddress, username, password))
  62. {
  63. ftp.Open();
  64. ftp.Login();
  65. foreach (var file in ftp.GetFiles("/"))
  66. {
  67. listinfo.Add(new ChannelTvListInfo { TVName = file.Name,
  68. LastWriteTime = Convert.ToDateTime(file.LastWriteTime).ToString("yyyy/MM/dd HH:mm") });
  69. }
  70. ftp.Dispose();
  71. ftp.Close();
  72. }
  73. return listinfo;
  74. }
  75. /// <summary>
  76. /// 服务停止的操作
  77. /// </summary>
  78. protected override void OnStop()
  79. {
  80. try
  81. {
  82. ThreadHello.Abort();
  83. WriteInLog("服务线程停止", false);
  84. System.Diagnostics.Trace.Write("线程停止");
  85. }
  86. catch (Exception ex)
  87. {
  88. System.Diagnostics.Trace.Write(ex.Message);
  89. }
  90. }
  91.  
  92. private void Hello()
  93. {
  94. try
  95. {
  96. fsw.Filter = "*.xml"; //设置监控文件的类型
  97. fsw.Path = @"D:\ChannelTvXML"; //设置监控的文件目录
  98. fsw.IncludeSubdirectories = true; //设置监控C盘目录下的所有子目录
  99. fsw.InternalBufferSize = ;
  100. fsw.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.Size | NotifyFilters.LastWrite |
  101. NotifyFilters.FileName | NotifyFilters.DirectoryName; ; //设置文件的文件名、目录名及文件的大小改动会触发Changed事件
  102. fsw.Changed += new FileSystemEventHandler(this.fsw_Changed);
  103. fsw.Error += new ErrorEventHandler(this.fsw_Error);
  104. fsw.EnableRaisingEvents = true;
  105. // Create the timer that will be used to deliver events. Set as disabled
  106. if (m_timer == null)
  107. {
  108. //设置定时器的回调函数。此时定时器未启动
  109. m_timer = new System.Threading.Timer(new TimerCallback(OnWatchedFileChange),
  110. null, Timeout.Infinite, Timeout.Infinite);
  111. }
  112.  
  113. }
  114. catch (Exception ex)
  115. {
  116. System.Diagnostics.Trace.Write(ex.Message);
  117. throw ex;
  118. }
  119.  
  120. Thread.Sleep();
  121.  
  122. }
  123. private void ThreadTime()
  124. {
  125. List<ChannelTvListInfo> lstNewTvInfo = listFTPFiles("60.208.140.170", "", "");
  126. WriteInLog(lstNewTvInfo.Count + "获取列表信息成功", false);
  127. // Create the timer that will be used to deliver events. Set as disabled
  128. if (m_timerDownLoad == null)
  129. {
  130. //设置定时器的回调函数。此时定时器未启动
  131. m_timerDownLoad = new System.Threading.Timer(new TimerCallback(DownLoadTvListInfo),
  132. null, Timeout.Infinite, Timeout.Infinite);
  133. }
  134. Thread.Sleep();
  135. }
  136. private void DownLoadTvListInfo(object state)
  137. {
  138. List<ChannelTvListInfo> lstOldTvInfo = new List<ChannelTvListInfo>();
  139. DirectoryInfo TheFolder = new DirectoryInfo(@"D:\ChannelTvXML");
  140. foreach (FileInfo NextFile in TheFolder.GetFileSystemInfos())
  141. {
  142. lstOldTvInfo.Add(new ChannelTvListInfo { TVName = NextFile.Name, LastWriteTime = NextFile.LastWriteTime.ToString("yyyy/MM/dd HH:mm") });
  143. }
  144. var result = lstNewTvInfo.Except(lstOldTvInfo, new ProductComparer()).ToList();
  145. if (result.Count > )
  146. {
  147. foreach (var item in result)
  148. {
  149. new FtpHelper().DownloadFtpFile("", "", "60.208.140.170", @"D:\ChannelTvXML", item.TVName);
  150. WriteInLog(item.TVName + "下载成功", false);
  151. }
  152. }
  153. }
  154. private void fsw_Changed(object sender, FileSystemEventArgs e)
  155. {
  156. Mutex mutex = new Mutex(false, "Wait");
  157. mutex.WaitOne();
  158. if (!files.Contains(e.Name))
  159. {
  160. files.Add(e.Name);
  161. }
  162. mutex.ReleaseMutex();
  163.  
  164. //重新设置定时器的触发间隔,并且仅仅触发一次
  165. m_timer.Change(TimeoutMillis, Timeout.Infinite);
  166.  
  167. }
  168. /// <summary>
  169. /// 定时器事件触发代码:进行文件的实际处理
  170. /// </summary>
  171. /// <param name="state"></param>
  172.  
  173. private void OnWatchedFileChange(object state)
  174. {
  175. _countTimerEvent++;
  176. WriteInLog(string.Format("TimerEvent {0}", _countTimerEvent.ToString("#00")), false);
  177. List<String> backup = new List<string>();
  178. Mutex mutex = new Mutex(false, "Wait");
  179. mutex.WaitOne();
  180. backup.AddRange(files);
  181. files.Clear();
  182. mutex.ReleaseMutex();
  183.  
  184. foreach (string file in backup)
  185. {
  186. _countFileChangeEvent++;
  187. WriteInLog(string.Format("FileEvent {0} :{1}文件已于{2}进行{3}", _countFileChangeEvent.ToString("#00"),
  188. file, DateTime.Now, "changed"), false);
  189. }
  190.  
  191. }
  192. private void fsw_Error(object sender, ErrorEventArgs e)
  193. {
  194. WriteInLog(e.GetException().Message, false);
  195. }
  196. /// <summary>
  197. /// 写入文件操作
  198. /// </summary>
  199. /// <param name="msg">写入内容</param>
  200. /// <param name="IsAutoDelete">是否删除</param>
  201. private void WriteInLog(string msg, bool IsAutoDelete)
  202. {
  203. try
  204. {
  205. string logFileName = @"D:\DownTvList_" + DateTime.Now.ToString("yyyyMMdd") + "_log.txt" + ""; // 文件路径
  206.  
  207. FileInfo fileinfo = new FileInfo(logFileName);
  208. if (IsAutoDelete)
  209. {
  210. if (fileinfo.Exists && fileinfo.Length >= )
  211. {
  212. fileinfo.Delete();
  213. }
  214. }
  215. using (FileStream fs = fileinfo.OpenWrite())
  216. {
  217. StreamWriter sw = new StreamWriter(fs);
  218. sw.BaseStream.Seek(, SeekOrigin.End);
  219. sw.Write("INFO-" + DateTime.Now.ToString() + "--日志内容为:" + msg + "\r\n");
  220. //sw.WriteLine("=====================================");
  221. sw.Flush();
  222. sw.Close();
  223. }
  224. }
  225. catch (Exception ex)
  226. {
  227. ex.ToString();
  228. }
  229. }
  230. }
  231.  
  232. }
  1. FtpHelper.cs 类代码
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9.  
  10. namespace WindowsService1
  11. {
  12. public class FtpHelper
  13. {
  14. private FtpWebRequest ftpRequest = null;
  15. private FtpWebResponse ftpResponse = null;
  16. private Stream ftpStream = null;
  17.  
  18. /// <summary>
  19. /// Get Filelist Name
  20. /// </summary>
  21. /// <param name="userId">ftp userid</param>
  22. /// <param name="pwd">ftp password</param>
  23. /// <param name="ftpIP">ftp ip</param>
  24. /// <returns></returns>
  25. public string[] GetFtpFileName(string userId, string pwd, string ftpIP, string filename)
  26. {
  27. string[] downloadFiles;
  28. StringBuilder result = new StringBuilder();
  29. try
  30. {
  31. ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/" + filename);
  32. ftpRequest.Credentials = new NetworkCredential(userId, pwd);
  33. ftpRequest.UseBinary = true;
  34. ftpRequest.UsePassive = true;
  35. ftpRequest.KeepAlive = true;
  36. ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
  37. ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
  38. ftpStream = ftpResponse.GetResponseStream();
  39. StreamReader ftpReader = new StreamReader(ftpStream);
  40. string line = ftpReader.ReadLine();
  41. while (line != null)
  42. {
  43. result.Append(line);
  44. result.Append("\n");
  45. line = ftpReader.ReadLine();
  46. }
  47. result.Remove(result.ToString().LastIndexOf('\n'), );
  48.  
  49. ftpReader.Close();
  50. ftpStream.Close();
  51. ftpResponse.Close();
  52. ftpRequest = null;
  53. return result.ToString().Split('\n');
  54.  
  55. }
  56. catch (Exception ex)
  57. {
  58. downloadFiles = null;
  59. return downloadFiles;
  60. }
  61. }
  62.  
  63. public string[] GetFtpFileName(string userId, string pwd, string ftpIP)
  64. {
  65. string[] downloadFiles;
  66. StringBuilder result = new StringBuilder();
  67. try
  68. {
  69. ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/");
  70. ftpRequest.Credentials = new NetworkCredential(userId, pwd);
  71. ftpRequest.UseBinary = true;
  72. ftpRequest.UsePassive = true;
  73. ftpRequest.KeepAlive = true;
  74. ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
  75. ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
  76. ftpStream = ftpResponse.GetResponseStream();
  77. StreamReader ftpReader = new StreamReader(ftpStream);
  78. string line = ftpReader.ReadLine();
  79. while (line != null)
  80. {
  81. result.Append(line);
  82. result.Append("\n");
  83. line = ftpReader.ReadLine();
  84. }
  85. result.Remove(result.ToString().LastIndexOf('\n'), );
  86.  
  87. ftpReader.Close();
  88. ftpStream.Close();
  89. ftpResponse.Close();
  90. ftpRequest = null;
  91. return result.ToString().Split('\n');
  92.  
  93. }
  94. catch (Exception ex)
  95. {
  96. downloadFiles = null;
  97. return downloadFiles;
  98. }
  99. }
  100.  
  101. /// <summary>
  102. ///从ftp服务器上下载文件的功能
  103. /// </summary>
  104. /// <param name="userId"></param>
  105. /// <param name="pwd"></param>
  106. /// <param name="ftpUrl">ftp地址</param>
  107. /// <param name="filePath"></param>
  108. /// <param name="fileName"></param>
  109. public void DownloadFtpFile(string userId, string pwd, string ftpUrl, string filePath, string fileName)
  110. {
  111. FtpWebRequest reqFTP = null;
  112. FtpWebResponse response = null;
  113. try
  114. {
  115. String onlyFileName = Path.GetFileName(fileName);
  116.  
  117. string downFileName = filePath + "\\" + onlyFileName;
  118. string url = "ftp://" + ftpUrl + "/" + fileName;
  119. if (File.Exists(downFileName))
  120. {
  121. DeleteDir(downFileName);
  122. }
  123.  
  124. FileStream outputStream = new FileStream(downFileName, FileMode.Create);
  125.  
  126. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
  127. reqFTP.Credentials = new NetworkCredential(userId, pwd);
  128. reqFTP.UseBinary = true;
  129. reqFTP.UsePassive = true;
  130. reqFTP.KeepAlive = true;
  131. reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
  132. response = (FtpWebResponse)reqFTP.GetResponse();
  133.  
  134. Stream ftpStream = response.GetResponseStream();
  135. long cl = response.ContentLength;
  136. int bufferSize = ;
  137. int readCount;
  138. byte[] buffer = new byte[bufferSize];
  139. readCount = ftpStream.Read(buffer, , bufferSize);
  140. while (readCount > )
  141. {
  142. outputStream.Write(buffer, , readCount);
  143. readCount = ftpStream.Read(buffer, , bufferSize);
  144. }
  145. ftpStream.Close();
  146. outputStream.Close();
  147. response.Close();
  148.  
  149. }
  150. catch (Exception ex)
  151. {
  152. throw ex;
  153. }
  154. }
  155.  
  156. /// 基姆拉尔森计算公式计算日期
  157. /// </summary>
  158. /// <param name="y">年</param>
  159. /// <param name="m">月</param>
  160. /// <param name="d">日</param>
  161. /// <returns>星期几</returns>
  162.  
  163. public static string CaculateWeekDay(int y, int m, int d)
  164. {
  165. if (m == || m == )
  166. {
  167. m += ;
  168. y--; //把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10则换算成:2003-13-10来代入公式计算。
  169. }
  170. int week = (d + * m + * (m + ) / + y + y / - y / + y / ) % ;
  171. string weekstr = "";
  172. switch (week)
  173. {
  174. case : weekstr = "星期一"; break;
  175. case : weekstr = "星期二"; break;
  176. case : weekstr = "星期三"; break;
  177. case : weekstr = "星期四"; break;
  178. case : weekstr = "星期五"; break;
  179. case : weekstr = "星期六"; break;
  180. case : weekstr = "星期日"; break;
  181. }
  182. return weekstr;
  183. }
  184. /// <summary>
  185. /// 返回不带后缀的文件名
  186. /// </summary>
  187. /// <param name="fileName"></param>
  188. /// <returns></returns>
  189. public static string GetFirstFileName(string fileName)
  190. {
  191. return Path.GetFileNameWithoutExtension(fileName);
  192. }
  193. #region 删除指定目录以及该目录下所有文件
  194. /// </summary><param name="dir">欲删除文件或者目录的路径</param>
  195. public static void DeleteDir(string dir)
  196. {
  197. CleanFiles(dir);//第一次删除文件
  198. CleanFiles(dir);//第二次删除目录
  199. }
  200. /// <summary>
  201. /// 删除文件和目录
  202. /// </summary>
  203. ///使用方法Directory.Delete( path, true)
  204. private static void CleanFiles(string dir)
  205. {
  206. if (!Directory.Exists(dir))
  207. {
  208. File.Delete(dir); return;
  209. }
  210. else
  211. {
  212. string[] dirs = Directory.GetDirectories(dir);
  213. string[] files = Directory.GetFiles(dir);
  214. if ( != dirs.Length)
  215. {
  216. foreach (string subDir in dirs)
  217. {
  218. if (null == Directory.GetFiles(subDir))
  219. { Directory.Delete(subDir); return; }
  220. else CleanFiles(subDir);
  221. }
  222. }
  223. if ( != files.Length)
  224. {
  225. foreach (string file in files)
  226. { File.Delete(file); }
  227. }
  228. else Directory.Delete(dir);
  229. }
  230. }
  231. #endregion
  232. }
  233. public class ChannelListInfo
  234. {
  235. // public string ChannelID { get; set; }
  236. public string WeekDate { get; set; }
  237. public string ChannelTV { get; set; }
  238. public string ChannelName { get; set; }
  239. public string ChannelType { get; set; }
  240. public string ChannelSummary { get; set; }
  241. // public string ChannelImg { get; set; }
  242.  
  243. public DateTime ChannelStartDate { get; set; }
  244. public DateTime ChannelEndDate { get; set; }
  245. // public DateTime? AddTime { get; set; }
  246. public DateTime? ChannelPlayDate { get; set; }
  247.  
  248. }
  249. public class ChannelTvListInfo
  250. {
  251. public string TVName { get; set; }
  252. public string LastWriteTime { get; set; }
  253. }
  254. // Custom comparer for the Product class
  255. public class ProductComparer : IEqualityComparer<ChannelTvListInfo>
  256. {
  257. // Products are equal if their names and product numbers are equal.
  258. public bool Equals(ChannelTvListInfo x, ChannelTvListInfo y)
  259. {
  260.  
  261. //Check whether the compared objects reference the same data.
  262. if (Object.ReferenceEquals(x, y)) return true;
  263.  
  264. //Check whether any of the compared objects is null.
  265. if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
  266. return false;
  267.  
  268. //Check whether the products' properties are equal.
  269. return x.TVName == y.TVName && x.LastWriteTime == y.LastWriteTime;
  270. }
  271.  
  272. // If Equals() returns true for a pair of objects
  273. // then GetHashCode() must return the same value for these objects.
  274.  
  275. public int GetHashCode(ChannelTvListInfo product)
  276. {
  277. //Check whether the object is null
  278. if (Object.ReferenceEquals(product, null)) return ;
  279.  
  280. //Get hash code for the Name field if it is not null.
  281. int hashProductName = product.TVName == null ? : product.TVName.GetHashCode();
  282.  
  283. //Get hash code for the Code field.
  284. int hashProductCode = product.LastWriteTime.GetHashCode();
  285.  
  286. //Calculate the hash code for the product.
  287. return hashProductName ^ hashProductCode;
  288. }
  289.  
  290. }
  291. }

C# 利用FTP自动下载xml文件后利用 FileSystemWatcher 监控目录下文件变化并自动更新数据库的更多相关文章

  1. shell脚本监控目录下文件被篡改时报警

    思路: 目录下文件被篡改的几种可能: 1.被修改 2.被删除 3.新增文件 md5命令详解 参数: -b 以二进制模式读入文件内容 -t 以文本模式读入文件内容 -c 根据已生成的md5值,对现存文件 ...

  2. 2.4 利用FTP服务器下载和上传目录

    利用FTP服务器下载目录 import os,sys from ftplib import FTP from mimetypes import guess_type nonpassive = Fals ...

  3. 安装debian 9.1后,中文环境下将home目录下文件夹改为对应的英文

    安装了debian 9.1后,中文环境下home目录下文件夹显示的是中文,相当不方便cd命令,改为对应的英文吧,需要用到的软件xdg-user-dirs-gtk #安装需要的软件 sudo apt i ...

  4. Linux下wget获取ftp下目录下文件

    如果某个目录下有一个文件可以使用ftp命令: get xxx 如果是某个目录下有多个文件(且不需要获取目录下子文件夹下的内容): mget * 如果是某个目录下有子目录希望获取所有子目录: wget ...

  5. Eclipse中.setting目录下文件介绍

    Eclipse项目中系统文件介绍 一. 写在前面 文章较长,可以直接到感兴趣的段落,或者直接关键字搜索: 请原谅作者掌握的编程语言少,这里只研究Java相关的项目: 每一个文件仅仅做一个常见内容的简单 ...

  6. 【转载】Eclipse中.setting目录下文件介绍

    原文:http://blog.csdn.net/huaweitman/article/details/52351394 Eclipse在新建项目的时候会自动生成一些文件.这些文件比如.project. ...

  7. as3 AIR 添加或删除ApplicationDirectory目录下文件

    AIR的文件目录静态类型有五种: File.userDirectory //指向用户文件夹 File.documentsDirectory //指向用户文档文件夹 File.desktopDirect ...

  8. linux 系统统计目录下文件夹的大小

    du -ah --max-depth=1     这个是我想要的结果  a表示显示目录下所有的文件和文件夹(不含子目录),h表示以人类能看懂的方式,max-depth表示目录的深度. du命令用来查看 ...

  9. linux 目录下文件批量植入和删除,按日期打包

    linux目录下文件批量植入 [root@greymouster http2]# find /usr/local/http2/htdocs/ -type f|xargs sed -i "   ...

随机推荐

  1. Uber优步北京第二、三组奖励政策

    优步北京第二.三组: 定义为​2015年6月1日至今激活的司机(以优步后台数据显示为准) 滴滴快车单单2.5倍,注册地址:http://www.udache.com/如何注册Uber司机(全国版最新最 ...

  2. python的bif介绍

    Python是面向对象的解释性程序设计语言,Python的语法简洁,特点是用空白符作为语句缩进. BIF(bulit in function)内置函数,就是Python自身提供的函数功能,编程者直接使 ...

  3. Java编辑环境搭建

    1.Java开发环境搭建 这里主要说的是在Windows系统下的环境搭建 JDK的安装 java的sdk简称JDK ,去其官方网站下载最近的JDK即可http://www.oracle.com/tec ...

  4. 6、Java并发编程:volatile关键字解析

    Java并发编程:volatile关键字解析 volatile这个关键字可能很多朋友都听说过,或许也都用过.在Java 5之前,它是一个备受争议的关键字,因为在程序中使用它往往会导致出人意料的结果.在 ...

  5. spring-boot、spring-data-jpa、hibernate整合

    一.Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. ...

  6. L011系统文件属性知识进阶详解小节

    L011系统文件属性知识进阶详解小节 这节课的内容相对来说较少,一上午加中午就听完了,现在总结一下,最后会有一个相关的面试题. 首先先附上一张图: 今天学习主要跟①和②有关,①为Inode 号 ②为文 ...

  7. android 几个工具方法

    集合几个工具方法,方便以后使用. 1.获取手机 分辨率屏幕: public static void printScreenInfor(Context context){ DisplayMetrics ...

  8. Qt-QSplashScreen-程序启动动画

    多数大型应用程序启动时可会在程序完全启动前显示一个启动画面,在程序完全启动后消失,程序启动画面可以显示相关产品的一些信息,使用户在等待程序启动时同时了解产品的相关功能,这也是一种宣传方式. 首先运行界 ...

  9. jmeter关联三种常用方法

    在LR中有自动关联跟手动关联,但在我看来手动关联更准确,在jmeter中,就只有手动关联 为什么要进行关联:对系统进行操作时,本次操作或下一次操作对服务器提交的请求,这参数里边有部分参数需要服务器返回 ...

  10. lesson 21 Daniel Mendoza

    lesson 21 Daniel Mendoza bare 赤裸的 :boxers fought with bare fists crude 天然的:crude sugar, crude oil 粗俗 ...