C# 建立 Windows Service 方法

 
C# 建立 Windows Service 方法
 
– 先係 Visual Studio 上, 以 Windows 服務 (Windows Services) 既 Project Template 建立 Project
 
– 係 Service1.cs 既 Property 上更改 ServiceName 為 “Testing Windows Service"
– 加入安裝程式 (Add Installer)
 
– 係 ProjectInstaller.cs -gt; serviceProcessInstaller 既 Property 上更改 Account 為 “LocalSystem"
 
– 更改 Service1.cs 程式碼
 

 
   using System;
   using System.Diagnostics;
   using System.ServiceProcess;
   using System.Data.SqlClient;
   using System.Threading;
 
   namespace WindowsService1
   {
      public partial class Service1 : ServiceBase
      {
         public Service1()
         {
            InitializeComponent();
            //WriteToEventLog(1234, "Start", "Test Start");
         }
 
         protected override void OnStart(string[] args)
         {
            //WriteToEventLog(1234, "Start 2", "Test Start 2");
            Timer t = new Timer(TimerCallback, null, 0, 10000);
         }
 
         private static Boolean WriteToEventLog(int EventId, String app, String Entry)
         {
            String AppName = app;
            EventLog objEventLog = new EventLog();
 
            EventLogEntryType EventType = EventLogEntryType.Information;
            String LogName = "Application";
 
            try
            {
               objEventLog.Source = AppName;
               objEventLog.WriteEntry(Entry, EventType, EventId);
 
               return true;
            }
            catch (Exception ex)
            {
               return false;
            }
         }
 
         private static void TimerCallback(Object o)
         {
            //WriteToEventLog(1234, "Start Timer", "Test Start Timer");
            try
            {
               String ConnectionString = @"<Connection String>";
               SqlConnection conn = new SqlConnection(ConnectionString);
               conn.Open();
 
               String SQLStatement = "INSERT INTO Service (Service_Date) VALUES ({fn Now()})";
 
               SqlCommand cmd = new SqlCommand(SQLStatement, conn);
               cmd.ExecuteNonQuery();
 
               conn.Dispose();
               cmd.Dispose();
               conn.Close();
 
            }catch(Exception ex){
               WriteToEventLog(1234, "Error", ex.Message);
            }
         }
 
         protected override void OnStop()
         {
         }
      }
   }
 

 
安裝 Windows Services – 以 InstallUtil.exe 安裝
– <%SystemRoot%>\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe
– <%SystemRoot%>\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe
 
安裝指令
InstallUtil "D:\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe"
 
移除指令
InstallUtil /u "D:\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe"