1.建立Windows項目,選擇"Windows服務"類型的項目。
2.在產生的Service1.cs中代碼中寫你需要的代碼,如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
Timer timer;
public Service1() { InitializeComponent(); }
protected override void OnStart(string[] args)
{
timer = new Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
timer.Dispose();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + "test.txt";
StreamWriter sw = null;
if (!File.Exists(filePath))
{
sw = File.CreateText(filePath);
}
else
{
sw = File.AppendText(filePath);
}
sw.Write("訪問時間:" + DateTime.Now.ToString() + Environment.NewLine);
sw.Close();
}
}
}
3.在和Service1.cs這個項目下在建立一個安裝程式類Installer1.cs,代碼如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
namespace WindowsService1
{
[RunInstaller(true)]
public partial class Installer1 : Installer
{
private System.ServiceProcess.ServiceProcessInstaller spInstaller;
private System.ServiceProcess.ServiceInstaller sInstaller;
public Installer1()
{
InitializeComponent();
// 建立ServiceProcessInstaller對象和ServiceInstaller對象
this.spInstaller = new System.ServiceProcess.ServiceProcessInstaller();
this.sInstaller = new System.ServiceProcess.ServiceInstaller();
// 設定ServiceProcessInstaller對象的帳號、使用者名稱和密碼等資訊
this.spInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
this.spInstaller.Password = null;
this.spInstaller.Username = null;
// 設定服務的名稱
this.sInstaller.ServiceName = "MyTestWindowsService1";
//設定服務啟動的方式
this.sInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.spInstaller, this.sInstaller });
}
}
}
4.產生工程,在bin目錄下會產生exe檔案。如果直接運行exe檔案的話,是不能執行的,需要使用安裝Windows服務用到一個名為InstallUtil.exe的命令列工具,開啟命令列工具,轉到InstallUtil.exe的目錄下,對應的目錄為:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe,然後執行InstallUtil.exe+待執行的exe檔案的目錄,如:InstallUtil.exe F:\MyProject\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe。執行成功後,會在Windows的服務中,出現了剛剛添加的服務的名稱。
開啟Windows服務列表方式:運行 --> 輸入services.msc
在列表中尋找一個叫MyTestWindowsService1 的服務,這個就是你建立安裝的服務
5.啟動該服務,這時開啟bin\Debug檔案夾,發現已經產生了一個test.txt的檔案,裡面記錄了時間。這說明服務已經正式開始執行。
6.卸載服務的操作也和簡單,開啟命令列工具,轉到C:\Windows\Microsoft.NET\Framework\v4.0.30319目錄,然後執行InstallUtil.exe -u F:\MyProject\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe命令就可以了。