.Net实现Windows服务安装完成后自动启动的两种方法

本文介绍了两种实现C#编写的Windows服务自动启动的方法:一是通过命令行启动服务;二是利用ServiceController对象来启动服务,并提供了详细的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

考虑到部署方便,我们一般都会将C#写的Windows服务制作成安装包。在服务安装完成以后,第一次还需要手动启动服务,这样非常不方便。

方法一:在安装完成事件里面调用命令行的方式启动服务

此操作之前要先设置下两个控件

设置serviceProcessInstaller1控件的Account属性为“LocalSystem
设置serviceInstaller1控件的StartType属性为"Automatic"

在服务器上添加安装程序,在private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)事件中,添加以下代码:

    /// <summary>
        /// 安装后自动启动服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
        {
            Process p = new Process
            {
                StartInfo =
                {
                    FileName = "cmd.exe",
                    UseShellExecute = false,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    CreateNoWindow = true
                }
            };
            p.Start();
            const string cmdString = "sc start 银医通服务平台1.0"; //cmd命令,银医通服务平台1.0为服务的名称
            p.StandardInput.WriteLine(cmdString);
            p.StandardInput.WriteLine("exit");
        }


查阅了网上的一些资料,这种方式虽可行,但觉得不够完美。好了,下面来看看如何更好地做到服务自动启动。

方法二:使用ServiceController对象

1.重写ProjectInstaller的Commit方法

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
namespace CleanExpiredSessionSeivice
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
        }

         public override void Commit(IDictionary savedState)
        {
            base.Commit(savedState);
            ServiceController sc = new ServiceController("银医通服务平台1.0");
            if(sc.Status.Equals(ServiceControllerStatus.Stopped))
            {
                sc.Start();
            }
        }
    }
}

2、在服务安装项目中添加名为 Commit的 Custome Action

在服务安装项目上右击,在弹出的菜单中选择View — Custom Actions

  1. image

     

    然后在Commit项上右击,选择Add Custom Action…,在弹出的列表框中选择Application Folder。最终结果如下:

    image

     

    需要注意的是,第二步操作是必不可少的,否则服务无法自动启动。我的个人理解是Commit Custom Action 会自动调用ProjectInstaller的Commit方法,Commit Custom Action 在这里扮演了一个调用者的角色。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值