C# 利用FTP自动下载xml文件后利用 FileSystemWatcher 监控目录下文件变化并自动更新数据库
- using FtpLib;
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.ServiceProcess;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace WindowsService1
- {
- public partial class Service1 : ServiceBase
- {
- private int TimeoutMillis = ; //定时器触发间隔
- private int _countFileChangeEvent = , _countTimerEvent = ;
- System.IO.FileSystemWatcher fsw = new System.IO.FileSystemWatcher();
- System.Threading.Timer m_timer = null;
- System.Threading.Timer m_timerDownLoad = null;
- List<String> files = new List<string>(); //记录待处理文件的队列
- private Thread ThreadHello;
- private Thread ThreadDownLoad;
- private List<ChannelTvListInfo> lstNewTvInfo;
- public Service1()
- {
- InitializeComponent();
- }
- //http://blog.csdn.net/hwt0101/article/details/8514291
- //http://www.cnblogs.com/mywebname/articles/1244745.html
- //http://www.cnblogs.com/jzywh/archive/2008/07/23/filesystemwatcher.html
- /// <summary>
- /// 服务启动的操作
- /// </summary>
- /// <param name="args"></param>
- protected override void OnStart(string[] args)
- {
- try
- {
- ThreadDownLoad = new Thread(new ThreadStart(ThreadTime));
- ThreadDownLoad.Start();
- ThreadHello = new Thread(new ThreadStart(Hello));
- ThreadHello.Start();
- WriteInLog("服务线程任务开始", false);
- System.Diagnostics.Trace.Write("线程任务开始");
- }
- catch (Exception ex)
- {
- System.Diagnostics.Trace.Write(ex.Message);
- throw ex;
- }
- }
- public List<ChannelTvListInfo> listFTPFiles(string FTPAddress, string username, string password)
- {
- List<ChannelTvListInfo> listinfo = new List<ChannelTvListInfo>();
- using (FtpConnection ftp = new FtpConnection(FTPAddress, username, password))
- {
- ftp.Open();
- ftp.Login();
- foreach (var file in ftp.GetFiles("/"))
- {
- listinfo.Add(new ChannelTvListInfo { TVName = file.Name,
- LastWriteTime = Convert.ToDateTime(file.LastWriteTime).ToString("yyyy/MM/dd HH:mm") });
- }
- ftp.Dispose();
- ftp.Close();
- }
- return listinfo;
- }
- /// <summary>
- /// 服务停止的操作
- /// </summary>
- protected override void OnStop()
- {
- try
- {
- ThreadHello.Abort();
- WriteInLog("服务线程停止", false);
- System.Diagnostics.Trace.Write("线程停止");
- }
- catch (Exception ex)
- {
- System.Diagnostics.Trace.Write(ex.Message);
- }
- }
- private void Hello()
- {
- try
- {
- fsw.Filter = "*.xml"; //设置监控文件的类型
- fsw.Path = @"D:\ChannelTvXML"; //设置监控的文件目录
- fsw.IncludeSubdirectories = true; //设置监控C盘目录下的所有子目录
- fsw.InternalBufferSize = ;
- fsw.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.Size | NotifyFilters.LastWrite |
- NotifyFilters.FileName | NotifyFilters.DirectoryName; ; //设置文件的文件名、目录名及文件的大小改动会触发Changed事件
- fsw.Changed += new FileSystemEventHandler(this.fsw_Changed);
- fsw.Error += new ErrorEventHandler(this.fsw_Error);
- fsw.EnableRaisingEvents = true;
- // Create the timer that will be used to deliver events. Set as disabled
- if (m_timer == null)
- {
- //设置定时器的回调函数。此时定时器未启动
- m_timer = new System.Threading.Timer(new TimerCallback(OnWatchedFileChange),
- null, Timeout.Infinite, Timeout.Infinite);
- }
- }
- catch (Exception ex)
- {
- System.Diagnostics.Trace.Write(ex.Message);
- throw ex;
- }
- Thread.Sleep();
- }
- private void ThreadTime()
- {
- List<ChannelTvListInfo> lstNewTvInfo = listFTPFiles("60.208.140.170", "", "");
- WriteInLog(lstNewTvInfo.Count + "获取列表信息成功", false);
- // Create the timer that will be used to deliver events. Set as disabled
- if (m_timerDownLoad == null)
- {
- //设置定时器的回调函数。此时定时器未启动
- m_timerDownLoad = new System.Threading.Timer(new TimerCallback(DownLoadTvListInfo),
- null, Timeout.Infinite, Timeout.Infinite);
- }
- Thread.Sleep();
- }
- private void DownLoadTvListInfo(object state)
- {
- List<ChannelTvListInfo> lstOldTvInfo = new List<ChannelTvListInfo>();
- DirectoryInfo TheFolder = new DirectoryInfo(@"D:\ChannelTvXML");
- foreach (FileInfo NextFile in TheFolder.GetFileSystemInfos())
- {
- lstOldTvInfo.Add(new ChannelTvListInfo { TVName = NextFile.Name, LastWriteTime = NextFile.LastWriteTime.ToString("yyyy/MM/dd HH:mm") });
- }
- var result = lstNewTvInfo.Except(lstOldTvInfo, new ProductComparer()).ToList();
- if (result.Count > )
- {
- foreach (var item in result)
- {
- new FtpHelper().DownloadFtpFile("", "", "60.208.140.170", @"D:\ChannelTvXML", item.TVName);
- WriteInLog(item.TVName + "下载成功", false);
- }
- }
- }
- private void fsw_Changed(object sender, FileSystemEventArgs e)
- {
- Mutex mutex = new Mutex(false, "Wait");
- mutex.WaitOne();
- if (!files.Contains(e.Name))
- {
- files.Add(e.Name);
- }
- mutex.ReleaseMutex();
- //重新设置定时器的触发间隔,并且仅仅触发一次
- m_timer.Change(TimeoutMillis, Timeout.Infinite);
- }
- /// <summary>
- /// 定时器事件触发代码:进行文件的实际处理
- /// </summary>
- /// <param name="state"></param>
- private void OnWatchedFileChange(object state)
- {
- _countTimerEvent++;
- WriteInLog(string.Format("TimerEvent {0}", _countTimerEvent.ToString("#00")), false);
- List<String> backup = new List<string>();
- Mutex mutex = new Mutex(false, "Wait");
- mutex.WaitOne();
- backup.AddRange(files);
- files.Clear();
- mutex.ReleaseMutex();
- foreach (string file in backup)
- {
- _countFileChangeEvent++;
- WriteInLog(string.Format("FileEvent {0} :{1}文件已于{2}进行{3}", _countFileChangeEvent.ToString("#00"),
- file, DateTime.Now, "changed"), false);
- }
- }
- private void fsw_Error(object sender, ErrorEventArgs e)
- {
- WriteInLog(e.GetException().Message, false);
- }
- /// <summary>
- /// 写入文件操作
- /// </summary>
- /// <param name="msg">写入内容</param>
- /// <param name="IsAutoDelete">是否删除</param>
- private void WriteInLog(string msg, bool IsAutoDelete)
- {
- try
- {
- string logFileName = @"D:\DownTvList_" + DateTime.Now.ToString("yyyyMMdd") + "_log.txt" + ""; // 文件路径
- FileInfo fileinfo = new FileInfo(logFileName);
- if (IsAutoDelete)
- {
- if (fileinfo.Exists && fileinfo.Length >= )
- {
- fileinfo.Delete();
- }
- }
- using (FileStream fs = fileinfo.OpenWrite())
- {
- StreamWriter sw = new StreamWriter(fs);
- sw.BaseStream.Seek(, SeekOrigin.End);
- sw.Write("INFO-" + DateTime.Now.ToString() + "--日志内容为:" + msg + "\r\n");
- //sw.WriteLine("=====================================");
- sw.Flush();
- sw.Close();
- }
- }
- catch (Exception ex)
- {
- ex.ToString();
- }
- }
- }
- }
- FtpHelper.cs 类代码
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- namespace WindowsService1
- {
- public class FtpHelper
- {
- private FtpWebRequest ftpRequest = null;
- private FtpWebResponse ftpResponse = null;
- private Stream ftpStream = null;
- /// <summary>
- /// Get Filelist Name
- /// </summary>
- /// <param name="userId">ftp userid</param>
- /// <param name="pwd">ftp password</param>
- /// <param name="ftpIP">ftp ip</param>
- /// <returns></returns>
- public string[] GetFtpFileName(string userId, string pwd, string ftpIP, string filename)
- {
- string[] downloadFiles;
- StringBuilder result = new StringBuilder();
- try
- {
- ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/" + filename);
- ftpRequest.Credentials = new NetworkCredential(userId, pwd);
- ftpRequest.UseBinary = true;
- ftpRequest.UsePassive = true;
- ftpRequest.KeepAlive = true;
- ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
- ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
- ftpStream = ftpResponse.GetResponseStream();
- StreamReader ftpReader = new StreamReader(ftpStream);
- string line = ftpReader.ReadLine();
- while (line != null)
- {
- result.Append(line);
- result.Append("\n");
- line = ftpReader.ReadLine();
- }
- result.Remove(result.ToString().LastIndexOf('\n'), );
- ftpReader.Close();
- ftpStream.Close();
- ftpResponse.Close();
- ftpRequest = null;
- return result.ToString().Split('\n');
- }
- catch (Exception ex)
- {
- downloadFiles = null;
- return downloadFiles;
- }
- }
- public string[] GetFtpFileName(string userId, string pwd, string ftpIP)
- {
- string[] downloadFiles;
- StringBuilder result = new StringBuilder();
- try
- {
- ftpRequest = (FtpWebRequest)FtpWebRequest.Create(ftpIP + "/");
- ftpRequest.Credentials = new NetworkCredential(userId, pwd);
- ftpRequest.UseBinary = true;
- ftpRequest.UsePassive = true;
- ftpRequest.KeepAlive = true;
- ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
- ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
- ftpStream = ftpResponse.GetResponseStream();
- StreamReader ftpReader = new StreamReader(ftpStream);
- string line = ftpReader.ReadLine();
- while (line != null)
- {
- result.Append(line);
- result.Append("\n");
- line = ftpReader.ReadLine();
- }
- result.Remove(result.ToString().LastIndexOf('\n'), );
- ftpReader.Close();
- ftpStream.Close();
- ftpResponse.Close();
- ftpRequest = null;
- return result.ToString().Split('\n');
- }
- catch (Exception ex)
- {
- downloadFiles = null;
- return downloadFiles;
- }
- }
- /// <summary>
- ///从ftp服务器上下载文件的功能
- /// </summary>
- /// <param name="userId"></param>
- /// <param name="pwd"></param>
- /// <param name="ftpUrl">ftp地址</param>
- /// <param name="filePath"></param>
- /// <param name="fileName"></param>
- public void DownloadFtpFile(string userId, string pwd, string ftpUrl, string filePath, string fileName)
- {
- FtpWebRequest reqFTP = null;
- FtpWebResponse response = null;
- try
- {
- String onlyFileName = Path.GetFileName(fileName);
- string downFileName = filePath + "\\" + onlyFileName;
- string url = "ftp://" + ftpUrl + "/" + fileName;
- if (File.Exists(downFileName))
- {
- DeleteDir(downFileName);
- }
- FileStream outputStream = new FileStream(downFileName, FileMode.Create);
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
- reqFTP.Credentials = new NetworkCredential(userId, pwd);
- reqFTP.UseBinary = true;
- reqFTP.UsePassive = true;
- reqFTP.KeepAlive = true;
- reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
- 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 > )
- {
- outputStream.Write(buffer, , readCount);
- readCount = ftpStream.Read(buffer, , bufferSize);
- }
- ftpStream.Close();
- outputStream.Close();
- response.Close();
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// 基姆拉尔森计算公式计算日期
- /// </summary>
- /// <param name="y">年</param>
- /// <param name="m">月</param>
- /// <param name="d">日</param>
- /// <returns>星期几</returns>
- public static string CaculateWeekDay(int y, int m, int d)
- {
- if (m == || m == )
- {
- m += ;
- y--; //把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10则换算成:2003-13-10来代入公式计算。
- }
- int week = (d + * m + * (m + ) / + y + y / - y / + y / ) % ;
- string weekstr = "";
- switch (week)
- {
- case : weekstr = "星期一"; break;
- case : weekstr = "星期二"; break;
- case : weekstr = "星期三"; break;
- case : weekstr = "星期四"; break;
- case : weekstr = "星期五"; break;
- case : weekstr = "星期六"; break;
- case : weekstr = "星期日"; break;
- }
- return weekstr;
- }
- /// <summary>
- /// 返回不带后缀的文件名
- /// </summary>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static string GetFirstFileName(string fileName)
- {
- return Path.GetFileNameWithoutExtension(fileName);
- }
- #region 删除指定目录以及该目录下所有文件
- /// </summary><param name="dir">欲删除文件或者目录的路径</param>
- public static void DeleteDir(string dir)
- {
- CleanFiles(dir);//第一次删除文件
- CleanFiles(dir);//第二次删除目录
- }
- /// <summary>
- /// 删除文件和目录
- /// </summary>
- ///使用方法Directory.Delete( path, true)
- private static void CleanFiles(string dir)
- {
- if (!Directory.Exists(dir))
- {
- File.Delete(dir); return;
- }
- else
- {
- string[] dirs = Directory.GetDirectories(dir);
- string[] files = Directory.GetFiles(dir);
- if ( != dirs.Length)
- {
- foreach (string subDir in dirs)
- {
- if (null == Directory.GetFiles(subDir))
- { Directory.Delete(subDir); return; }
- else CleanFiles(subDir);
- }
- }
- if ( != files.Length)
- {
- foreach (string file in files)
- { File.Delete(file); }
- }
- else Directory.Delete(dir);
- }
- }
- #endregion
- }
- public class ChannelListInfo
- {
- // public string ChannelID { get; set; }
- public string WeekDate { get; set; }
- public string ChannelTV { get; set; }
- public string ChannelName { get; set; }
- public string ChannelType { get; set; }
- public string ChannelSummary { get; set; }
- // public string ChannelImg { get; set; }
- public DateTime ChannelStartDate { get; set; }
- public DateTime ChannelEndDate { get; set; }
- // public DateTime? AddTime { get; set; }
- public DateTime? ChannelPlayDate { get; set; }
- }
- public class ChannelTvListInfo
- {
- public string TVName { get; set; }
- public string LastWriteTime { get; set; }
- }
- // Custom comparer for the Product class
- public class ProductComparer : IEqualityComparer<ChannelTvListInfo>
- {
- // Products are equal if their names and product numbers are equal.
- public bool Equals(ChannelTvListInfo x, ChannelTvListInfo y)
- {
- //Check whether the compared objects reference the same data.
- if (Object.ReferenceEquals(x, y)) return true;
- //Check whether any of the compared objects is null.
- if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
- return false;
- //Check whether the products' properties are equal.
- return x.TVName == y.TVName && x.LastWriteTime == y.LastWriteTime;
- }
- // If Equals() returns true for a pair of objects
- // then GetHashCode() must return the same value for these objects.
- public int GetHashCode(ChannelTvListInfo product)
- {
- //Check whether the object is null
- if (Object.ReferenceEquals(product, null)) return ;
- //Get hash code for the Name field if it is not null.
- int hashProductName = product.TVName == null ? : product.TVName.GetHashCode();
- //Get hash code for the Code field.
- int hashProductCode = product.LastWriteTime.GetHashCode();
- //Calculate the hash code for the product.
- return hashProductName ^ hashProductCode;
- }
- }
- }
C# 利用FTP自动下载xml文件后利用 FileSystemWatcher 监控目录下文件变化并自动更新数据库的更多相关文章
- shell脚本监控目录下文件被篡改时报警
思路: 目录下文件被篡改的几种可能: 1.被修改 2.被删除 3.新增文件 md5命令详解 参数: -b 以二进制模式读入文件内容 -t 以文本模式读入文件内容 -c 根据已生成的md5值,对现存文件 ...
- 2.4 利用FTP服务器下载和上传目录
利用FTP服务器下载目录 import os,sys from ftplib import FTP from mimetypes import guess_type nonpassive = Fals ...
- 安装debian 9.1后,中文环境下将home目录下文件夹改为对应的英文
安装了debian 9.1后,中文环境下home目录下文件夹显示的是中文,相当不方便cd命令,改为对应的英文吧,需要用到的软件xdg-user-dirs-gtk #安装需要的软件 sudo apt i ...
- Linux下wget获取ftp下目录下文件
如果某个目录下有一个文件可以使用ftp命令: get xxx 如果是某个目录下有多个文件(且不需要获取目录下子文件夹下的内容): mget * 如果是某个目录下有子目录希望获取所有子目录: wget ...
- Eclipse中.setting目录下文件介绍
Eclipse项目中系统文件介绍 一. 写在前面 文章较长,可以直接到感兴趣的段落,或者直接关键字搜索: 请原谅作者掌握的编程语言少,这里只研究Java相关的项目: 每一个文件仅仅做一个常见内容的简单 ...
- 【转载】Eclipse中.setting目录下文件介绍
原文:http://blog.csdn.net/huaweitman/article/details/52351394 Eclipse在新建项目的时候会自动生成一些文件.这些文件比如.project. ...
- as3 AIR 添加或删除ApplicationDirectory目录下文件
AIR的文件目录静态类型有五种: File.userDirectory //指向用户文件夹 File.documentsDirectory //指向用户文档文件夹 File.desktopDirect ...
- linux 系统统计目录下文件夹的大小
du -ah --max-depth=1 这个是我想要的结果 a表示显示目录下所有的文件和文件夹(不含子目录),h表示以人类能看懂的方式,max-depth表示目录的深度. du命令用来查看 ...
- linux 目录下文件批量植入和删除,按日期打包
linux目录下文件批量植入 [root@greymouster http2]# find /usr/local/http2/htdocs/ -type f|xargs sed -i " ...
随机推荐
- Uber优步北京第二、三组奖励政策
优步北京第二.三组: 定义为2015年6月1日至今激活的司机(以优步后台数据显示为准) 滴滴快车单单2.5倍,注册地址:http://www.udache.com/如何注册Uber司机(全国版最新最 ...
- python的bif介绍
Python是面向对象的解释性程序设计语言,Python的语法简洁,特点是用空白符作为语句缩进. BIF(bulit in function)内置函数,就是Python自身提供的函数功能,编程者直接使 ...
- Java编辑环境搭建
1.Java开发环境搭建 这里主要说的是在Windows系统下的环境搭建 JDK的安装 java的sdk简称JDK ,去其官方网站下载最近的JDK即可http://www.oracle.com/tec ...
- 6、Java并发编程:volatile关键字解析
Java并发编程:volatile关键字解析 volatile这个关键字可能很多朋友都听说过,或许也都用过.在Java 5之前,它是一个备受争议的关键字,因为在程序中使用它往往会导致出人意料的结果.在 ...
- spring-boot、spring-data-jpa、hibernate整合
一.Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. ...
- L011系统文件属性知识进阶详解小节
L011系统文件属性知识进阶详解小节 这节课的内容相对来说较少,一上午加中午就听完了,现在总结一下,最后会有一个相关的面试题. 首先先附上一张图: 今天学习主要跟①和②有关,①为Inode 号 ②为文 ...
- android 几个工具方法
集合几个工具方法,方便以后使用. 1.获取手机 分辨率屏幕: public static void printScreenInfor(Context context){ DisplayMetrics ...
- Qt-QSplashScreen-程序启动动画
多数大型应用程序启动时可会在程序完全启动前显示一个启动画面,在程序完全启动后消失,程序启动画面可以显示相关产品的一些信息,使用户在等待程序启动时同时了解产品的相关功能,这也是一种宣传方式. 首先运行界 ...
- jmeter关联三种常用方法
在LR中有自动关联跟手动关联,但在我看来手动关联更准确,在jmeter中,就只有手动关联 为什么要进行关联:对系统进行操作时,本次操作或下一次操作对服务器提交的请求,这参数里边有部分参数需要服务器返回 ...
- lesson 21 Daniel Mendoza
lesson 21 Daniel Mendoza bare 赤裸的 :boxers fought with bare fists crude 天然的:crude sugar, crude oil 粗俗 ...