调用windows服务来监视文件夹状态

记录一下过程

打开vs 新建一个解决方案再新建一个windows服务项目,再新建一个数据库处理类库直接用的SqlHelper,再添加一个应用程序配置文件app.config

项目结构如下:

windows服务代码

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Diagnostics;
  6 using System.Linq;
  7 using System.ServiceProcess;
  8 using System.Text;
  9 using System.Diagnostics.PerformanceData;
 10 using System.IO;
 11 using System.Data.SqlClient;
 12 namespace FileMonitorService
 13 {
 14     public partial class Service1 : ServiceBase
 15     {
 16         private System.Diagnostics.PerformanceCounter fileCreateCounter;
 17         private System.Diagnostics.PerformanceCounter fileDeleteCounter;
 18         private System.Diagnostics.PerformanceCounter fileRenameCounter;
 19         private System.Diagnostics.PerformanceCounter fileChangeCounter;
 20         private bool servicePaused = false;
 21         public Service1()
 22         {
 23             InitializeComponent();
 24         }
 25         protected override void OnStart(string[] args)
 26         {
 27             FileSystemWatcher curWatcher = new FileSystemWatcher();
 28 
 29             curWatcher.BeginInit();
 30             curWatcher.IncludeSubdirectories = true;
 31             curWatcher.Path =
 32     System.Configuration.ConfigurationSettings.AppSettings["FileMonitorDirectory"];
 33             curWatcher.Changed += new FileSystemEventHandler(OnFileChanged);
 34             curWatcher.Created += new FileSystemEventHandler(OnFileCreated);
 35             curWatcher.Deleted += new FileSystemEventHandler(OnFileDeleted);
 36             curWatcher.Renamed += new RenamedEventHandler(OnFileRenamed);
 37             curWatcher.EnableRaisingEvents = true;
 38             curWatcher.EndInit();
 39 
 40         }
 41         private void OnFileChanged(Object source, FileSystemEventArgs e)
 42         {
 43             if (servicePaused == false)
 44             {
 45                 Writelog(DateTime.Now.ToString() + "修改了" + e.FullPath.ToString(), e.Name);
 46             }
 47         }
 48 
 49         private void OnFileRenamed(Object source, RenamedEventArgs e)
 50         {
 51             if (servicePaused == false)
 52             {
 53                 Writelog(DateTime.Now.ToString() + "重命名了" + e.FullPath.ToString(), e.Name);
 54             }
 55         }
 56 
 57         private void OnFileCreated(Object source, FileSystemEventArgs e)
 58         {
 59             if (servicePaused == false)
 60             {
 61                 //File.Open
 62                 
 63                 Writelog(DateTime.Now.ToString() + "创建了" + e.FullPath.ToString(),e.Name);
 64                 
 65             }
 66         }
 67         protected void Writelog(string log,string name)
 68         {
 69             string logpath = System.Configuration.ConfigurationSettings.AppSettings["log"];
 70             StreamWriter sw = new StreamWriter(logpath,true,System.Text.Encoding.Default);
 71             try
 72             {
 73                 //SqlConnection conn = new SqlConnection("Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=FileMonitorServiceLog;Data Source=192.168.3.22");
 74                 //SqlCommand cmd = new SqlCommand("insert into LogList(logcontent)values('" + log + "')", conn);
 75                 //conn.Open();
 76                 //cmd.ExecuteNonQuery();
 77                 //conn.Close();
 78                 Rifa.ITPlatform.DB.SqlHelper sqlh = new Rifa.ITPlatform.DB.SqlHelper();
 79                 sqlh.RunSqlStr("insert into LogList(logcontent,directory)values('" + log + "','" + name + "')");
 80                 sw.WriteLine(log);
 81                 sw.Flush();
 82                 sw.Close();
 83             }
 84             catch(Exception ex)
 85             {                
 86                 sw.WriteLine("文件写入失败"+ex.Message);
 87                 sw.Close();
 88             }
 89 
 90         }
 91 
 92         private void OnFileDeleted(Object source, FileSystemEventArgs e)
 93         {
 94             if (servicePaused == false)
 95             {
 96                 Writelog(DateTime.Now.ToString() + "删除了" + e.FullPath.ToString(), e.Name);
 97             }
 98         } 
 99 
100         protected override void OnStop()
101         {
102             if (fileChangeCounter.RawValue != 0)
103             {
104                 fileChangeCounter.IncrementBy(-fileChangeCounter.RawValue);
105             }
106             if (fileDeleteCounter.RawValue != 0)
107             {
108                 fileDeleteCounter.IncrementBy(-fileDeleteCounter.RawValue);
109             }
110             if (fileRenameCounter.RawValue != 0)
111             {
112                 fileRenameCounter.IncrementBy(-fileRenameCounter.RawValue);
113             }
114             if (fileCreateCounter.RawValue != 0)
115             {
116                 fileCreateCounter.IncrementBy(-fileCreateCounter.RawValue);
117             }
118         }
119         protected override void OnPause()
120         {
121             servicePaused = true;
122         }
123 
124         protected override void OnContinue()
125         {
126             servicePaused = false;
127         } 
128 
129     }
130 }

app.config配置信息

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <configuration>
 3   <appSettings>
 4     <add key="FileMonitorDirectory" value="E:\learn_project\WindowsService1\test\"/>
 5     <add key="log" value="E:\learn_project\WindowsService1\log.txt"/>    
 6   </appSettings>
 7   <connectionStrings>
 8     <add name="conn" connectionString="Password=123456;Persist Security Info=True;User ID=sa;Initial Catalog=FileMonitorServiceLog;Data Source=192.168.3.22" />
 9   </connectionStrings>
10 </configuration>

把应用程序设置成winodws服务的命令如下

sc create FileMonitorService type= own start= auto binpath= E:\learn_project\WindowsService1\FileMonitorService\bin\Debug\FileMonitorService.exe displayname= FileMonitorService

然后到服务里启动这个服务就可以了

最后来一张数据库表信息的截图

原文地址:https://www.cnblogs.com/your568/p/2780941.html