首页 / C#开发 / 正文

C#/.NET应用程序编程开发中如何实现不使用InstallUtil.exe安装Windows服务(Windows Service)?

2626 1 发布于: 2019-06-04 读完约需8分钟

问题描述

在C#/.NET应用程序编程开发中,如果开发一个标准的.NET Windows 服务程序(不使用像Topshelf这样的第三方Windows服务组件),当你在安装/卸载这个服务程序时,需要借助InstallUtil.exe才能完成。

那么,有没有可能使用C#实现不使用InstallUtil.exe而可以完成Windows服务安装/卸载的方法呢?比如类似的命令:

MyService.exe -install

答案是肯定的。

方案一

借助System.ServiceProcess.dll这个程序集来实现无需InstallUtil.exe安装Windows服务的方法,如下:

[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

方案二

使用ManagedInstaller类中的InstallHelper()方法,如:

using System;
using System.Collections.Generic;
using System.Configuration.Install; 
using System.IO;
using System.Linq;
using System.Reflection; 
using System.ServiceProcess;
using System.Text;

static void Main(string[] args)
{
    if (System.Environment.UserInteractive)
    {
        string parameter = string.Concat(args);
        switch (parameter)
        {
            case "--install":
                ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
                break;
            case "--uninstall":
                ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
                break;
        }
    }
    else
    {
        ServiceBase.Run(new WindowsService());
    }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: C#/ASP.NET应用程序编程开发中如何设置Session的超时时间?

下一篇: C#/.NET应用程序编程开发中如何从一个集合List<T>中删除在另一个集合List<T>中的所有元素?

本文永久链接码友网 » C#/.NET应用程序编程开发中如何实现不使用InstallUtil.exe安装Windows服务(Windows Service)?

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册