C # Implementation Development Windows service implementation automatically download files from the FTP server (self-setting sub/Time execution)

Source: Internet
Author: User

Recently in doing a daily fixed-point from FTP automatically download the program. XML and update the functionality to the database. The first thought is to use the FileSystemWatcher to monitor whether the files downloaded to a directory change, if the change is to do the appropriate action, and then use the timer to set the interval for how long to download. And then I thought about it. Use the WINDWOS service to achieve it.

:


Log logs executed:

INFO-2016/5/24 0:30:07--Log content is: 0/30/7 time trigger info-2016/5/24 1:30:07--log content is: 1/30/7 for time Trigger info-2016/5/24 2:30:07-- The log content is: 2/30/7 time trigger info-2016/5/24 3:30:07--log content is: 3/30/7 time trigger info-2016/5/24 4:30:07--log content: 4/30/ 7 Time trigger info-2016/5/24 5:30:07--log content is: 5/30/7 time trigger info-2016/5/24 6:30:07--log content is: 6/30/7 for TIME Trigger INFO-2016/5/24 7:30:07--log content is: 7/30/7 time trigger info-2016/5/24 7:30:07--log content is: timerevent 01info-2016/5/24 7:30:07--log content: TimerEvent 01: Get a total of 77 program list information successfully. INFO-2016/5/24 7:31:08--Log content is: The server and the local program list information compared to start. INFO-2016/5/24 7:31:08--Log content is: Get the program list to be updated a total of 77 info-2016/5/24 7:31:08--log content is: Fileevent 01:btv-1 (HD). The download of the. xml file starts again. INFO-2016/5/24 7:31:08--Log content is: Fileevent 01:btv-1 (HD). xml file content was changed and re-downloaded successfully on 2016/05/24 00:01. INFO-2016/5/24 7:31:08--Log content is: Fileevent 01:btv-1 (HD). The modification time after download of the XML file starts with the server modification time synchronization. INFO-2016/5/24 7:31:08--Log content is: Fileevent 01:btv-1 (HD). The modified time after download of the XML file has been successfully synchronized with the server modification time. INFO-2016/5/24 7:31:08--Log content is: Fileevent 02:cctv-1 (HD). xml file re-download begins. INFO-2016/5/24 7:31:08--Log content is: Fileevent 02:cctv-1 (HD). XML textContent was changed and re-downloaded successfully on 2016/05/24 00:01. INFO-2016/5/24 7:31:08--Log content is: Fileevent 02:cctv-1 (HD). The modification time after download of the XML file starts with the server modification time synchronization. INFO-2016/5/24 7:31:08--Log content is: Fileevent 02:cctv-1 (HD). The modified time after download of the XML file has been successfully synchronized with the server modification time. INFO-2016/5/24 7:31:33--Log content is: Fileevent 77: Heilongjiang satellite TV (HD). The XML file is re-downloaded to start. INFO-2016/5/24 7:31:33--Log content is: Fileevent 77: Heilongjiang satellite TV (HD). The contents of the XML file were changed and re-downloaded successfully on 2016/05/24 00:01. INFO-2016/5/24 7:31:33--Log content is: Fileevent 77: Heilongjiang satellite TV (HD). The modification time after the XML file download begins with the server modification time synchronization. INFO-2016/5/24 7:31:33--Log content is: Fileevent 77: Heilongjiang satellite TV (HD). The modification time after the XML file download has started to synchronize successfully with the server modification time. INFO-2016/5/24 8:31:08--Log content is: 8/31/8 time trigger info-2016/5/24 9:31:08--log content is: 9/31/8 for time Trigger info-2016/5/24 10:31:08-- The log content is: 10/31/8 time trigger info-2016/5/24 11:31:08--log content is: 11/31/8 time trigger info-2016/5/24 12:31:08--log content: 12/31/ 8 time trigger info-2016/5/24 13:31:08--log content is: 13/31/8 time trigger info-2016/5/24 14:31:08--log content is: 14/31/8 for TIME Trigger INFO-2016/5 /24 15:31:08--Log content is: 15/31/8 time trigger info-2016/5/24 16:31:08--log content is: 16/31/8 time trigger info-2016/5/24 17:31:08--log content as : 17/31/8 for TIME Trigger INFO-2016/5/24 18:31:08--log content is: 18/31/8 time trigger info-2016/5/24 19:31:08--log content is: 19/31/8 time trigger info-2016/5/24 20:31:08--log content is: 20/ 31/8 time trigger info-2016/5/24 21:31:08--log content is: 21/31/8 time trigger info-2016/5/24 22:31:08--log content is: 22/31/ 8 time trigger info-2016/5/24 23:31:08--log content is: 23/31/8 for TIME Trigger

Implementation code:

Download Ftplib.dll and then reference references in the project

Using ftplib;using system;using system.collections.generic;using system.diagnostics;using System.IO;using system.linq;using system.serviceprocess;using system.threading;namespace Windowsservice1{public partial class service1:servicebase{private int _countfilechangeevent = 0, _counttimerevent = 0;private Thread threaddownload;public Se Rvice1 () {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//http://www.cnblogs.com/hfzsjz/ archive/2011/01/07/1929898.html///<summary>///Service initiated operation///</summary>///<param name= "args" ></ param>protected override void OnStart (string[] args) {try{eventlog.writeentry ("Monitoring Server and local program list information thread task start");// Description of the source in the application event in the System Event Viewer Writeinlog ("Monitoring Server with local program list information thread task start", false); System.Timers.Timer t = new System.Timers.Timer ();//t.interval = 60000;      T.interval = 60 * 60 * 1000; t.elapsed + = new SysteM.timers.elapsedeventhandler (begindowload);//The event is executed at time of arrival, T.autoreset = true;//setting is performed once (false) or always (true); t. Enabled = true;//Whether the System.Timers.Timer.Elapsed event is performed; T.start ();} catch (Exception ex) {System.Diagnostics.Trace.Write (ex. Message); throw ex;}} <summary>///Timing check and execution method///</summary>//<param name= "source" ></param>//<param NA Me= "E" ></param> public void Begindowload (object source, System.Timers.ElapsedEventArgs e) {int intminute = e. Signaltime.minute;int Intsecond = E.signaltime.second;int inthours = e.signaltime.hour;//set to start executing the program 07:30 every day WriteInLog ( inthours+ "/" + Intminute + "/" + Intsecond + "Time Trigger", false), if (inthours = = 07)///timing setting, judging ticks && Intminute = = 10{try{system.timers.timer TT = (System.Timers.Timer) source;tt. Enabled = False;downloadtvlistinfo (); TT. Enabled = true;} catch (Exception err) {Writeinlog (err. Message, False);}}} 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>///Service Stop operation//</summary>protected override void OnStop () {try{threaddownload.abort (); Writeinlog ("Monitor server with local program list information thread task stop", false); System.Diagnostics.Trace.Write ("Monitor server and local program list information thread task stop"); EventLog.WriteEntry ("Monitoring Server and local program list information thread task stopped");} catch (Exception ex) {System.Diagnostics.Trace.Write (ex. Message);}} Private List<channeltvlistinfo> lstnewtvinfo, lstoldtvinfo = new list<channeltvlistinfo> ();p rivate void Downloadtvlistinfo () {_counttimerevent++; Writeinlog (String. Format ("timerevent {0}", _counttimerevent.tostring ("#00")), false); lstnewtvinfo = ListftpfiLes ("222.206.159.xx", "xx", "xx"); Writeinlog (String. Format ("timerevent {0}: A total of {1} program list information was successfully obtained. ", _counttimerevent.tostring (" #00 "), Lstnewtvinfo.count), false); lstoldtvinfo = new list<channeltvlistinfo> () ;D irectoryinfo thefolder = new DirectoryInfo (@ "D:\GoodLook\UpLoadImg\ChannelTvXML"); foreach (FileInfo nextfile in Thefolder.getfilesysteminfos ()) {Lstoldtvinfo.add (new Channeltvlistinfo {tvname = nextfile.name, LastWriteTime =      NextFile.LastWriteTime.ToString ("Yyyy/mm/dd hh:mm")}); Thread.Sleep (60000); Threaddownload = new Thread (new ThreadStart (Test)); Threaddownload.start (); Writeinlog ("The server and the local program list information are compared to start. ", false); System.Diagnostics.Trace.Write ("Thread task Start");} public void Test () {Try{var result = Lstnewtvinfo.except (Lstoldtvinfo, New Productcomparer ()). ToList (); Writeinlog ("Get a list of programs to update" + result.) Count+ "A", false), if (result. Count > 0) {foreach (var item in result) {_countfilechangeevent++; Writeinlog (String. Format ("fileevent {0}: {1} file re-download started. ", _countfilechangeevent.tostring (" #00 "), iteM.tvname), false); new Ftphelper (). Downloadftpfile ("xx", "xx", "222.206.159.xx", @ "D:\GoodLook\UpLoadImg\ChannelTvXML", item. Tvname); Writeinlog (String. Format ("fileevent {0}: {1} file contents have been {2} for {3}", _countfilechangeevent.tostring ("#00"), item. Tvname, item. LastWriteTime, "changed and re-downloaded successfully. "), false); Writeinlog (String. Format ("fileevent {0}: {1} file was downloaded after the modification time starts with the server modification time synchronization. ", _countfilechangeevent.tostring (" #00 "), item. Tvname), false); File.setlastwritetime (@ "D:\GoodLook\UpLoadImg\ChannelTvXML\" + item.) Tvname,convert.todatetime (New Ftphelper (). Getdatetimestamp ("222.206.159.xx", item. Tvname, "xx", "Quanmeiti"). XX ("Yyyy/mm/dd hh:mm tt"))); Writeinlog (String. Format ("fileevent {0}: {1}" the file was downloaded after the modification time started to synchronize successfully with server modification time. ", _countfilechangeevent.tostring (" #00 "), item. Tvname), False);}} Else{writeinlog ("No Server TV listings update", false);}} catch {}thread.sleep (60000);} <summary>///Write file operation///</summary>///<param name= "msg" > Write content </param>///<param name= " Isautodelete "> whether to delete</param>private void Writeinlog (String msg, bool isautodelete) {try{string LogFileName = @ "D:\GoodLook\UpLoadImg\ Channellog\downtvlist_ "+ DateTime.Now.ToString (" yyyyMMdd ") +" _log.txt "+" "; File path FileInfo FileInfo = new FileInfo (LogFileName), if (Isautodelete) {if (FileInfo. Exists && FileInfo. Length >= 1024x768) {FileInfo. Delete ();}} using (FileStream fs = FileInfo. OpenWrite ()) {StreamWriter SW = new StreamWriter (fs); SW. Basestream.seek (0, seekorigin.end); SW. Write ("info-" + DateTime.Now.ToString () + "--Log content is:" + msg + "\ r \ n"); SW. Flush (); SW. Close ();}} catch (Exception ex) {ex. ToString ();}}}

Implementing the download file from FTP method

<summary>///the ability to download files from an FTP server//</summary>///<param name= "UserId" ></param>///<param Name= "pwd" ></param>///<param name= "Ftpurl" >ftp address </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 = 2048;int readcount;byte[] buffer = new Byte[buffersize];readcount = ftpStream.Read (buffer , 0, BufferSize), while (Readcount > 0) {outputstream.write (buffer, 0, readcount); readcount = ftpstream.read (buffer, 0, buffersize);} Ftpstream.close (); Outputstream.close (); response. Close ();} catch (Exception ex) {throw ex;}}


Setting up the WIDNWOS service does not introduce much. Such as:






C # Implementation Development Windows service implementation automatically download files from the FTP server (self-setting sub/Time execution)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.