Windows服务的安装与卸载

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pan_junbiao/article/details/84105168

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)点击文件,执行卸载服务。

猜你喜欢

转载自blog.csdn.net/pan_junbiao/article/details/84105168