分享

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

 行走在理想边缘 2019-01-08

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


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


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

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

 

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

 




[csharp] view plaincopy






  1. /// <summary>  

  2.     /// 安装后自动启动服务  

  3.     /// </summary>  

  4.     /// <param name="sender"></param>  

  5.     /// <param name="e"></param>  

  6.     private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)  

  7.     {  

  8.         Process p = new Process  

  9.         {  

  10.             StartInfo =  

  11.             {  

  12.                 FileName = "cmd.exe",  

  13.                 UseShellExecute = false,  

  14.                 RedirectStandardInput = true,  

  15.                 RedirectStandardOutput = true,  

  16.                 RedirectStandardError = true,  

  17.                 CreateNoWindow = true  

  18.             }  

  19.         };  

  20.         p.Start();  

  21.         const string cmdString = "sc start 银医通服务平台1.0"//cmd命令,银医通服务平台1.0为服务的名称  

  22.         p.StandardInput.WriteLine(cmdString);  

  23.         p.StandardInput.WriteLine("exit");  

  24.     }  







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


方法二:使用ServiceController对象



1.重写ProjectInstaller的Commit方法





  1. using System;  

  2. using System.Collections;  

  3. using System.Collections.Generic;  

  4. using System.ComponentModel;  

  5. using System.Configuration.Install;  

  6. using System.Linq;  

  7. using System.ServiceProcess;  

  8. namespace CleanExpiredSessionSeivice  

  9. {  

  10.     [RunInstaller(true)]  

  11.     public partial class ProjectInstaller : System.Configuration.Install.Installer  

  12.     {  

  13.         public ProjectInstaller()  

  14.         {  

  15.             InitializeComponent();  

  16.         }  

  17.   

  18.          public override void Commit(IDictionary savedState)  

  19.         {  

  20.             base.Commit(savedState);  

  21.             ServiceController sc = new ServiceController("银医通服务平台1.0");  

  22.             if(sc.Status.Equals(ServiceControllerStatus.Stopped))  

  23.             {  

  24.                 sc.Start();  

  25.             }  

  26.         }  

  27.     }  

  28. }  



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


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


image


 


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


image


 


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



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多