C# Developing Windows Service to Realize Automatically Downloading Files from FTP Server

Time:2019-10-7

Recently, I am working on a daily function of automatically downloading program. XML from FTP and updating it to database. First of all, think of using FileSystemWatcher to monitor whether the files that are downloaded to a directory are changed or not. If changes occur, perform corresponding operations, then use timer to set up how long it takes to download. Later, I think about using windwos services to achieve.

Design sketch:

Log logs executed:

INFO-2016/5/240:30:07 -- Log content: 0/30/7 time trigger
INFO-2016/5/241:30:07 -- Log content: 1/30/7 time trigger
INFO-2016/5/242:30:07 -- Log content: 2/30/7 time trigger
INFO-2016/5/243:30:07 -- Log content: 3/30/7 time trigger
INFO-2016/5/244:30:07 -- Log content: 4/30/7 time trigger
INFO-2016/5/245:30:07 -- Log content: 5/30/7 time trigger
INFO-2016/5/246:30:07 -- Log content: 6/30/7 time trigger
INFO-2016/5/247:30:07 -- Log content: 7/30/7 time trigger
INFO-2016/5/247:30:07 -- TimerEvent 01
INFO-2016/5/247:30:07 -- TimerEvent 01 :共获取77个节目列表信息成功。
INFO-2016/5/247:31:08 - The content of the log is to start by comparing the information of the server with the information of the local program list.
INFO-2016/5/247:31:08 -- Log content: get a total of 77 updates to the program list
INFO-2016/5/247:31:08 -- FileEvent 01: BTV-1 (HD). XML file download to start again.
INFO-2016/5/247:31:08 - FileEvent 01: BTV-1 (HD). XML file content has been changed and downloaded successfully in 2016/05/2400:01.
INFO-2016/5/247:31:08 -- The content of the log is: FileEvent 01: BTV-1 (HD). XML file download modification time begins to synchronize with the server modification time.
INFO-2016/5/247:31:08 -- The content of the log is: FileEvent 01:BTV-1 (HD). XML file download modification time began to synchronize with the server modification time successfully.
INFO-2016/5/247:31:08 -- Log content: FileEvent 02:CCTV-1 (HD). XML file to start downloading again.
INFO-2016/5/247:31:08 - FileEvent 02: CCTV-1 (HD). XML file content has been changed and downloaded successfully in 2016/05/2400:01.
INFO-2016/5/247:31:08 -- The content of the log is: FileEvent 02:CCTV-1 (HD). XML file download modification time begins to synchronize with the server modification time.
INFO-2016/5/247:31:08 - The content of the log is: FileEvent 02:CCTV-1 (HD). XML file download modification time began to synchronize with the server modification time successfully.
The contents of the INFO-2016/5/24 7:31:33-- log are: FileEvent 77: the download of the.Xml file of the satellite TV (hd).
INFO-2016/5/247:31:33 - The content of the log is FileEvent 77: Heilongjiang Satellite TV (HD). The content of the XML file has been changed and downloaded successfully in 2016/05/2400:01.
The contents of the INFO-2016/5/24 7:31:33-- log are: FileEvent 77: the modification time after the download of.Xml files is started synchronously with the server modification time.
The contents of INFO-2016/5/24 7:31:33-- log are: FileEvent 77: the modification time after downloading.Xml files is started synchronously with the server modification time.
INFO-2016/5/248:31:08 -- Log content: 8/31/8 time trigger
INFO-2016/5/249:31:08 -- Log content: 9/31/8 time trigger
INFO-2016/5/24 10:31:08 -- Log content: 10/31/8 time trigger
INFO-2016/5/24 11:31:08 -- Log content: 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: 13/31/8 time trigger
INFO-2016/5/24 14:31:08 -- Log content: 14/31/8 time trigger
INFO-2016/5/24 15:31:08 -- Log content: 15/31/8 time trigger
INFO-2016/5/24 16:31:08 -- Log content: 16/31/8 time trigger
INFO-2016/5/24 17:31:08 -- Log content: 17/31/8 time trigger
INFO-2016/5/24 18:31:08 -- Log content: 18/31/8 time trigger
INFO-2016/5/24 19:31:08 -- Log content: 19/31/8 time trigger
INFO-2016/5/24 20:31:08 -- Log content: 20/31/8 time trigger
INFO-2016/5/24 21:31:08 -- Log content: 21/31/8 time trigger
INFO-2016/5/24 22:31:08 -- Log content: 22/31/8 time trigger
INFO-2016/5/24 23:31:08 -- Log content: 23/31/8 time trigger

Implementation code:

Download ftplib.dll and refer to it 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 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
 //http://www.cnblogs.com/hfzsjz/archive/2011/01/07/1929898.html
 /// <summary>
 /// Operation of service startup
 /// </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 Sources in Application Events in System Event Viewer 
 WriteInLog ("Monitoring Server and 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 (Begin Dow Load); // Execute the event at the time of arrival; 
 T. AutoReset = true; // Set whether to execute once (false) or always (true); 
 T. Enabled = true; // Execute System. Timers. Timer. Elapsed events; 
 t.Start();
 }
 catch (Exception ex)
 {
 System.Diagnostics.Trace.Write(ex.Message);
 throw ex;
 }
 }
 /// <summary> 
 /// Check regularly and execute methods 
 /// </summary> 
 /// <param name="source"></param> 
 /// <param name="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 a daily 07:30 to start executing the program
 WriteInLog (intHours +"/"+intMinute +"/"+intSecond + "time trigger", false);
 If (intHours == 07) /// timing settings, judge minutes and seconds & 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>
 /// Operation of Service Stop
 /// </summary>
 protected override void OnStop()
 {
 try
 {
 ThreadDownLoad.Abort();
 WriteInLog ("Monitoring Server and Local Program List Information Thread Task Stop", false);
 System. Diagnostics. Trace. Write ("Monitoring Server and Local Program List Information Thread Task Stop");
 EventLog. WriteEntry ("Monitoring Server and Local Program List Information Thread Task Stop");
 }
 catch (Exception ex)
 {
 System.Diagnostics.Trace.Write(ex.Message);
 }
 }
 
 private List<ChannelTvListInfo> lstNewTvInfo, lstOldTvInfo = new List<ChannelTvListInfo>();
 private 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 obtained successfully. ", countTimerEvent. ToString (" 00"), lstNewTvInfo. Count, false);
 lstOldTvInfo = new List<ChannelTvListInfo>();
 
 DirectoryInfo TheFolder = new DirectoryInfo(@"D:\Hello\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 ("Start by comparing the server with the local program list information. "False";
 System. Diagnostics. Trace. Write ("Thread Task Start");
 }
 
 public void Test()
 {
 try
 {
 var result = lstNewTvInfo.Except(lstOldTvInfo, new ProductComparer()).ToList();
 WriteInLog ("Get a total list of programs to be updated"+result.Count+"individual", false);
 if (result.Count > 0)
 {
  foreach (var item in result)
  {
  _countFileChangeEvent++;
  WriteInLog (string. Format ("FileEvent {0}: {1} File download starts again. "CountFileChangeEvent. ToString (" 00"),
  item.TVName), false);
 
  new FtpHelper().DownloadFtpFile("xx", "xx", "222.206.159.xx", @"D:\Hello\UpLoadImg\ChannelTvXML", item.TVName);
 
  WriteInLog (string. Format ("FileEvent {0}: {1} file content has been {3} in {2}, _countFileChangeEvent. ToString ("#00"),
        Item. TVName, Item. LastWriteTime, "Changed and downloaded successfully. "(false);
 
  WriteInLog (string. Format ("FileEvent {0}: {1} The modification time after downloading the file starts synchronizing with the server modification time. "CountFileChangeEvent. ToString (" 00"),
 item.TVName), false);
  File.SetLastWriteTime(@"D:\Hello\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 modification time after downloading the file begins to synchronize with the server modification time successfully. "CountFileChangeEvent. ToString (" 00"),
 item.TVName), false);
 
  }
 }
 else
 {
  WriteInLog ("No Server TV Program List Update", false);
 }
 
 }
 catch { }
 Thread.Sleep(60000);
 }
 
 /// <summary>
 /// Write file operation
 /// </summary>
 /// <param name="msg">Write content </param>
 /// <param name="IsAutoDelete">Delete </param>
 private void WriteInLog(string msg, bool IsAutoDelete)
 {
 try
 {
 String logFileName = @ "D: Hello UpLoadImg ChannelLog DownTvList_" + DateTime. Now. ToString ("yyyyMMdd") + "_log. txt" +"; //file path
 
 FileInfo fileinfo = new FileInfo(logFileName);
 if (IsAutoDelete)
 {
  if (fileinfo.Exists && fileinfo.Length >= 1024)
  {
  fileinfo.Delete();
  }
 }
 using (FileStream fs = fileinfo.OpenWrite())
 {
  StreamWriter sw = new StreamWriter(fs);
  sw.BaseStream.Seek(0, SeekOrigin.End);
  Sw.Write ("INFO-"+DateTime.Now.ToString()+"--The content of the log is:"+msg +"\r\n";
  sw.Flush();
  sw.Close();
 }
 }
 catch (Exception ex)
 {
 ex.ToString();
 }
 }
 }
 
}

Implementation of Downloading Files from FTP

/// <summary>
 /// Function of downloading files from 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 widnwos services is not much introduced. The following picture:

The above is the whole content of this article. I hope it will be helpful to everyone’s study, and I hope you will support developpaer more.

Recommended Today

Details of multi-path and large capacity hard disk mount under CentOS

I. application environment and requirementsBlade servers connect HP storage through fiber switches, forming a 2×2 link The storage capacity of the operating system for CentOS 6.4 64 bit mount is 2.5t Based on this application environment, two problems need to be solved: In order to ensure the stability and transmission performance of the link, multi-path […]