当前位置:   article > 正文

C# 利用FTP自动下载xml文件后利用 FileSystemWatcher 监控目录下文件变化并自动更新数据库_c#filesystemwatcher能不能监听ftp

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


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号