每次要寫個windows服務時總是忘記一些細節,於是又去百度搜,其實並不復雜,於是這次自己簡單整理下,記錄下操作步驟,沒任何技術含量,只是簡單記錄:
一.添加windows服務
1.設計頁面,右鍵添加安裝程序
2.右鍵serviceInstaller,修改幾個屬性:
3.右鍵serviceProcessInstaller1,修改account屬性:
4.修改service1.cs服務名稱與serviceInstall中服務名稱的屬性一致
5.service1.cs代碼中,添加計時器,完善邏輯代碼,
protected override void OnStart(string[] args) { System.Timers.Timer timer = new System.Timers.Timer();//添加一個計時器 timer.Elapsed += ShowDate; //綁定事件 timer.Interval = 10 * 1000;//間隔多久執行一次服務,單位毫秒 timer.Enabled=true; //這一點不要忘記 } protected override void OnStop() { } private void ShowDate(object sender, System.Timers.ElapsedEventArgs e) { log.Info("當前時間:" + DateTime.Now.ToString(CultureInfo.InvariantCulture)); }
6.安裝與運行:
進入如下目錄:C:\Windows\Microsoft.NET\Framework64\v4.0.30319,將InstallUtil.exe復制到改windows服務bin/debug下:
7.cmd命令窗口(管理員身份運行),進入到該debug目錄下,之后的安裝,運行命令如下:
安裝:InstallUtil.exe WindowsDemo0205.exe
卸載:InstallUtil.exe -u WindowsDemo0205.exe
運行:net start MyService
停止:net stop MyService
二.加入log4Net記錄日志
1.nuget包工具給項目添加log4Net
2.修改配置文件App.config,添加相關節點
3.使用log記錄日志的代碼頁面類中添加日志記錄對象:
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
4.最容易忽視且最重要一點,Properties下的AssemblyInfo.cs文件添加如下代碼:
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
控制台應用程序中也要注意別忘記修改AssemblyInfo.cs文件。
PS:如果是Web程序,Global配置文件下,Application_Start方法中添加代碼(log4net.config配成了一個單獨文件):
protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(Server.MapPath("/log4net.config")));
}
以上內容僅作備忘記錄