Windows服務的安裝與卸載

Windows服務的安裝與卸載。

1、服務信息的設置

首先創建一個Windows服務項目,本示例中的項目名稱爲:MyTest.WindowsService。

編寫服務啓動和關閉方法,記錄一些日誌信息,方便後續查看服務的狀態。

using System;
using System.ServiceProcess;
using System.Text;
using System.IO;

namespace MyTest.WindowsService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            WriteLog("服務啓動"); 
        }

        protected override void OnStop()
        {
            WriteLog("服務關閉"); 
        }

        /// <summary>
        /// 記錄日誌
        /// </summary>
        private void WriteLog(string message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "/MyLog.txt";
            using (StreamWriter txt = new StreamWriter(path, true, Encoding.Default))
            {
                txt.Flush();
                txt.WriteLine("時間:" + DateTime.Now);
                txt.WriteLine("內容:" + message);
                txt.WriteLine("------------------------");
                txt.Close();
            }
        }
    }
}

1.1 添加安裝程序

雙擊Service1.cs文件 —> 切換到Service1.cs[設計]界面 —>  右擊選擇“添加安裝程序”。

這時項目中會自動添加了一個新類 ProjectInstaller.cs 類,和兩個安裝控件 ServiceProcessInstaller 和 ServiceInstaller。

1.2 設置ServiceProcessInstaller控件信息

選中“serviceProcessInstaller1” 控件,F4打開屬性面板。

將Account屬性改爲 LocalSystem。

1.3 設置ServiceInstaller控件信息

選中“serviceInstaller1” 控件,F4打開屬性面板。

Description:服務程序的描述信息。
DisplayName:服務程序顯示的名稱。
ServiceName:指示系統用於標識此服務的名稱。
StartType:指定如何啓動服務 (Manual:服務安裝後,必須手動啓動;Automatic:每次計算機重新啓動時,服務都會自動啓動;Disabled:服務無法啓動)。

1.4 生成項目

選擇“Release”,編譯生成項目。

本示例中生成後的項目在 D:\MyTestProject\MyTest.WindowsService\bin\Release\MyTest.WindowsService.exe。

 

2、服務的安裝與卸載(方式一

方式一:使用CMD命令。

安裝命令:

installutil.exe D:\MyTestProject\MyTest.WindowsService\bin\Release\MyTest.WindowsService.exe

卸載命令:

installutil.exe /u D:\MyTestProject\MyTest.WindowsService\bin\Release\MyTest.WindowsService.exe

2.1 安裝服務

(1)開始 —> 運行 —> 鍵入cmd,打開命令窗口。

(2)進入安裝程序工具 (Installutil.exe)的目錄底下,命令:cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

(3)安裝服務,命令:installutil.exe D:\MyTestProject\MyTest.WindowsService\bin\Release\MyTest.WindowsService.exe

2.2 卸載服務

(1)卸載服務,命令:installutil.exe /u D:\MyTestProject\MyTest.WindowsService\bin\Release\MyTest.WindowsService.exe

 

3、服務的安裝與卸載(方式二)

方式二:使用bat批處理文件。

3.1 安裝服務

(1)創建MyServiceInstaller.bat批處理文件。

(2)打開該文件,輸入命令:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil D:\MyTestProject\MyTest.WindowsService\bin\Release\MyTest.WindowsService.exe
pause

(3)點擊文件,執行安裝服務。

3.2 卸載服務

(1)創建MyServiceUnInstaller.bat批處理文件。

(2)打開該文件,輸入命令:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /u D:\MyTestProject\MyTest.WindowsService\bin\Release\MyTest.WindowsService.exe
pause

(3)點擊文件,執行卸載服務。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章