zoukankan      html  css  js  c++  java
  • 使windows服务安装名称可配置

    有时,我们安装的windows服务可能是个框架,在同一服务器上可能服务于不同的系统,为了使服务名称不冲突,需要把服务名称更改为可配置。 因为ServiceInstaller能直接设置安装服务的名称和描述,所以很容易就能写出下面的代码:

    serviceInstaller.ServiceName = ConfigurationManager.AppSetting["ServiceName"];
    serviceInstaller.Description = ConfigurationManager.AppSetting["ServiceDescription"];

    编译执行安装,可惜抛出了异常,安装失败了。

    失败的原因是,执行安装服务的程序是InstallUtil.exe,安装阶段不会自动加载服务的app.config配置文件,只会加载全局的machine.config,需改为手动加载app.config并读取。 确定解决思路后,我写出了下面的代码:

    var targetDirectory = AppDomain.CurrentDomain.BaseDirectory;
    var configPath = Path.Combine(targetDirectory, "Service.exe");
    var config = ConfigurationManager.OpenExeConfiguration(configPath);
    serviceInstaller.ServiceName = config.AppSettings.Settings["ServiceName"].Value;
    serviceInstaller.Description = config.AppSettings.Settings["ServiceDescription"].Value;

    再次编译运行,发现本机上安装成功了:),整个程序打包交给另一个同事在服务器上安装,发现安装过程又出错了。。。 过去看了一下,发现错误的原因是,本机安装时,InstallUtil程序我是放在和服务同一目录,而服务器上的InstallUtil是和服务在不同目录。看来AppDomain.CurrentDomain.BaseDirectory获取到的是InstallUtil的应用程序域目录路径,而不是服务的。 之后使用反射来解决了这个问题,代码如下:

    var path = System.Reflection.Assembly.GetExecutingAssembly().Location;
    var targetDirectory = System.IO.Path.GetDirectoryName(path);
    var configPath = Path.Combine(targetDirectory, "Service.exe");
    var config = ConfigurationManager.OpenExeConfiguration(configPath);
    serviceInstaller.ServiceName = config.AppSettings.Settings["ServiceName"].Value;
    serviceInstaller.Description = config.AppSettings.Settings["ServiceDescription"].Value;
  • 相关阅读:
    package.json 字段全解析 share
    Git 使用方法
    浅谈移动前端的最佳实践(转)
    node启动服务后,窗口不能关闭。pm2了解一下
    WebSocket--客户端
    布局:多列等高布局方法
    uni-app调用支付宝、微信支付
    scss 入门基础
    mac生成iOS证书(配图)
    通过扫码打开IOS的App Store下载APP(Android版暂时没找到解决方法)
  • 原文地址:https://www.cnblogs.com/vento/p/2858141.html
Copyright © 2011-2022 走看看