C#操作注册服务卸载服务启动服务停止服务..

  1. using System;  
  2. using System.Configuration.Install;  
  3. using System.Collections;  
  4. using System.Collections.Specialized;  
  5.   
  6. IDictionary stateSaver = new Hashtable();  
  7. 一、安装服务:  
  8. private void InstallService(IDictionary stateSaver, string filepath)  
  9.   
  10.         {  
  11.   
  12.             try  
  13.   
  14.             {  
  15.   
  16.                 System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("ServiceName");  
  17.   
  18.                 if(!ServiceIsExisted("ServiceName"))  
  19.   
  20.                 {  
  21.   
  22.                     //Install Service  
  23.   
  24.                     AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();  
  25.   
  26.                     myAssemblyInstaller.UseNewContext = true;  
  27.   
  28.                     myAssemblyInstaller.Path =filepath;  
  29.   
  30.                     myAssemblyInstaller.Install(stateSaver);  
  31.   
  32.                     myAssemblyInstaller.Commit(stateSaver);  
  33.   
  34.                     myAssemblyInstaller.Dispose();  
  35.   
  36.                     //--Start Service  
  37.   
  38.                     service.Start();  
  39.   
  40.                 }  
  41.   
  42.                 else  
  43.   
  44.                 {  
  45.   
  46.                     if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)  
  47.   
  48.                     {  
  49.   
  50.                         service.Start();  
  51.   
  52.                     }  
  53.   
  54.                 }  
  55.   
  56.             }  
  57.   
  58.             catch (Exception ex)  
  59.   
  60.             {  
  61.   
  62.                 throw new Exception("installServiceError\n" + ex.Message);  
  63.   
  64.             }  
  65.   
  66.         }  
  67.   
  68. 或者  
  69.          /// <summary>  
  70.         /// 安装服务  
  71.         /// </summary>  
  72.         /// <param name="p_Path">指定服务文件路径</param>  
  73.         /// <param name="p_ServiceName">返回安装完成后的服务名</param>  
  74.         /// <returns>安装信息 正确安装返回""</returns>  
  75.         public static string InsertService(string p_Path, ref string p_ServiceName)  
  76.         {  
  77.             if (!File.Exists(p_Path)) return "文件不存在!";  
  78.             p_ServiceName = "";  
  79.             FileInfo _InsertFile = new FileInfo(p_Path);  
  80.             IDictionary _SavedState = new Hashtable();  
  81.             try  
  82.             {  
  83.                 //加载一个程序集,并运行其中的所有安装程序。  
  84.                 AssemblyInstaller _AssemblyInstaller = new AssemblyInstaller(p_Path, new string[] { "/LogFile=" + _InsertFile.DirectoryName + "\\" + _InsertFile.Name.Substring(0, _InsertFile.Name.Length - _InsertFile.Extension.Length) + ".log" });  
  85.                 _AssemblyInstaller.UseNewContext = true;  
  86.                 _AssemblyInstaller.Install(_SavedState);  
  87.                 _AssemblyInstaller.Commit(_SavedState);  
  88.                 Type[] _TypeList = _AssemblyInstaller.Assembly.GetTypes();//获取安装程序集类型集合  
  89.                 for (int i = 0; i != _TypeList.Length; i++)  
  90.                 {  
  91.                     if (_TypeList[i].BaseType.FullName == "System.Configuration.Install.Installer")  
  92.                     {  
  93.                         //找到System.Configuration.Install.Installer 类型  
  94.                         object _InsertObject = System.Activator.CreateInstance(_TypeList[i]);//创建类型实列  
  95.                         FieldInfo[] _FieldList = _TypeList[i].GetFields(BindingFlags.NonPublic | BindingFlags.Instance);  
  96.                         for (int z = 0; z != _FieldList.Length; z++)  
  97.                         {  
  98.                             if (_FieldList[z].FieldType.FullName == "System.ServiceProcess.ServiceInstaller")  
  99.                             {  
  100.                                 object _ServiceInsert = _FieldList[z].GetValue(_InsertObject);  
  101.                                 if (_ServiceInsert != null)  
  102.                                 {  
  103.                                     p_ServiceName = ((ServiceInstaller)_ServiceInsert).ServiceName;  
  104.                                     return "";  
  105.                                 }  
  106.                             }  
  107.                         }  
  108.                     }  
  109.                 }  
  110.                 return "";  
  111.             }  
  112.             catch (Exception ex)  
  113.             {  
  114.                 return ex.Message;  
  115.             }  
  116.         }  
  117.   
  118. 二、卸载windows服务:  
  119.   
  120.         private void UnInstallService(string filepath)  
  121.   
  122.         {  
  123.   
  124.             try  
  125.   
  126.             {  
  127.   
  128.                 if (ServiceIsExisted("ServiceName"))  
  129.   
  130.                 {  
  131.   
  132.                     //UnInstall Service  
  133.   
  134.                     AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();  
  135.   
  136.                     myAssemblyInstaller.UseNewContext = true;  
  137.   
  138.                     myAssemblyInstaller.Path = filepath;  
  139.   
  140.                     myAssemblyInstaller.Uninstall(null);  
  141.   
  142.                     myAssemblyInstaller.Dispose();  
  143.   
  144.                 }  
  145.   
  146.             }  
  147.   
  148.             catch (Exception ex)  
  149.   
  150.             {  
  151.   
  152.                 throw new Exception("unInstallServiceError\n" + ex.Message);  
  153.   
  154.             }  
  155.   
  156.         }  
  157.   
  158. 三、判断window服务是否存在:  
  159.   
  160.         private bool ServiceIsExisted(string serviceName)  
  161.   
  162.         {  
  163.   
  164.             ServiceController[] services = ServiceController.GetServices();  
  165.   
  166.             foreach (ServiceController s in services)  
  167.   
  168.             {  
  169.   
  170.                 if (s.ServiceName == serviceName)  
  171.   
  172.                 {  
  173.   
  174.                     return true;  
  175.   
  176.                 }  
  177.   
  178.             }  
  179.   
  180.             return false;  
  181.   
  182.         }  
  183.   
  184. 四、启动服务:  
  185.   
  186. private void StartService(string serviceName)  
  187.   
  188.         {  
  189.   
  190.             if (ServiceIsExisted(serviceName))  
  191.   
  192.             {  
  193.   
  194.                 System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);  
  195.   
  196.                 if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)  
  197.   
  198.                 {  
  199.   
  200.                     service.Start();  
  201.   
  202.                     for (int i = 0; i < 60; i++)  
  203.   
  204.                     {  
  205.   
  206.                         service.Refresh();  
  207.   
  208.                         System.Threading.Thread.Sleep(1000);  
  209.   
  210.                         if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)  
  211.   
  212.                         {  
  213.   
  214.                             break;  
  215.   
  216.                         }  
  217.   
  218.                         if (i == 59)  
  219.   
  220.                         {  
  221.   
  222.                             throw new Exception(startServiceError.Replace("$s$", serviceName));  
  223.   
  224.                         }  
  225.   
  226.                     }  
  227.   
  228.                 }  
  229.   
  230.             }  
  231.   
  232.         }  
  233. 另外方法  
  234.         /// <summary>  
  235.         /// 启动服务  
  236.         /// </summary>  
  237.         /// <param name="serviceName"></param>  
  238.         /// <returns></returns>  
  239.         public static bool ServiceStart(string serviceName)  
  240.         {  
  241.             try  
  242.             {  
  243.                 ServiceController service = new ServiceController(serviceName);  
  244.                 if (service.Status == ServiceControllerStatus.Running)  
  245.                 {  
  246.                     return true;  
  247.                 }  
  248.                 else  
  249.                 {  
  250.                     TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10);  
  251.   
  252.                     service.Start();  
  253.   
  254.   
  255.                     service.WaitForStatus(ServiceControllerStatus.Running, timeout);  
  256.                 }  
  257.             }  
  258.             catch  
  259.             {  
  260.   
  261.                 return false;  
  262.             }  
  263.             return true;  
  264.   
  265.         }  
  266.   
  267. 五、停止服务:  
  268.   
  269.         private void StopService(string serviceName)  
  270.   
  271.         {  
  272.   
  273.             if (ServiceIsExisted(serviceName))  
  274.   
  275.             {  
  276.   
  277.                 System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);  
  278.   
  279.                 if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)  
  280.   
  281.                 {  
  282.   
  283.                     service.Stop();  
  284.   
  285.                     for (int i = 0; i < 60; i++)  
  286.   
  287.                     {  
  288.   
  289.                         service.Refresh();  
  290.   
  291.                         System.Threading.Thread.Sleep(1000);  
  292.   
  293.                         if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)  
  294.   
  295.                         {  
  296.   
  297.                             break;  
  298.   
  299.                         }  
  300.   
  301.                         if (i == 59)  
  302.   
  303.                         {  
  304.   
  305.                             throw new Exception(stopServiceError.Replace("$s$", serviceName));  
  306.   
  307.                         }  
  308.   
  309.                     }  
  310.   
  311.                 }  
  312.   
  313.             }  
  314.   
  315.         }  
  316. 另外一方法:  
  317.          /// <summary>  
  318.         /// 停止服务  
  319.         /// </summary>  
  320.         /// <param name="serviseName"></param>  
  321.         /// <returns></returns>  
  322.         public static bool ServiceStop(string serviseName)  
  323.         {  
  324.             try  
  325.             {  
  326.                 ServiceController service = new ServiceController(serviseName);  
  327.                 if (service.Status == ServiceControllerStatus.Stopped)  
  328.                 {  
  329.                     return true;  
  330.                 }  
  331.                 else  
  332.                 {  
  333.                     TimeSpan timeout = TimeSpan.FromMilliseconds(1000 * 10);  
  334.                     service.Stop();  
  335.                     service.WaitForStatus(ServiceControllerStatus.Running, timeout);  
  336.                 }  
  337.             }  
  338.             catch  
  339.             {  
  340.   
  341.                 return false;  
  342.             }  
  343.             return true;  
  344.         }  
  345. 六 修改服务的启动项  
  346.          /// <summary>  
  347.         /// 修改服务的启动项 2为自动,3为手动  
  348.         /// </summary>  
  349.         /// <param name="startType"></param>  
  350.         /// <param name="serviceName"></param>  
  351.         /// <returns></returns>  
  352.         public static bool ChangeServiceStartType(int startType, string serviceName)  
  353.         {  
  354.             try  
  355.             {  
  356.                 RegistryKey regist = Registry.LocalMachine;  
  357.                 RegistryKey sysReg = regist.OpenSubKey("SYSTEM");  
  358.                 RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet");  
  359.                 RegistryKey services = currentControlSet.OpenSubKey("Services");  
  360.                 RegistryKey servicesName = services.OpenSubKey(serviceName, true);  
  361.                 servicesName.SetValue("Start", startType);  
  362.             }  
  363.             catch (Exception ex)  
  364.             {  
  365.   
  366.                 return false;  
  367.             }  
  368.             return true;  
  369.   
  370.   
  371.         }  
  372.   
  373. 七 获取服务启动类型   
  374.         /// <summary>  
  375.         /// 获取服务启动类型 2为自动 3为手动 4 为禁用  
  376.         /// </summary>  
  377.         /// <param name="serviceName"></param>  
  378.         /// <returns></returns>  
  379.         public static string GetServiceStartType(string serviceName)  
  380.         {  
  381.   
  382.             try  
  383.             {  
  384.                 RegistryKey regist = Registry.LocalMachine;  
  385.                 RegistryKey sysReg = regist.OpenSubKey("SYSTEM");  
  386.                 RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet");  
  387.                 RegistryKey services = currentControlSet.OpenSubKey("Services");  
  388.                 RegistryKey servicesName = services.OpenSubKey(serviceName, true);  
  389.                 return servicesName.GetValue("Start").ToString();  
  390.             }  
  391.             catch (Exception ex)  
  392.             {  
  393.   
  394.                 return string.Empty;  
  395.             }  
  396.   
  397.         }  
  398.   
  399. 八 验证服务是否启动  服务是否存在  
  400.          /// <summary>  
  401.         /// 验证服务是否启动  
  402.         /// </summary>  
  403.         /// <returns></returns>  
  404.         public static bool ServiceIsRunning(string serviceName)  
  405.         {  
  406.             ServiceController service = new ServiceController(serviceName);  
  407.             if (service.Status == ServiceControllerStatus.Running)  
  408.             {  
  409.                 return true;  
  410.             }  
  411.             else  
  412.             {  
  413.                 return false;  
  414.             }  
  415.         }  
  416.   
  417.         /// <summary>  
  418.         /// 服务是否存在  
  419.         /// </summary>  
  420.         /// <param name="serviceName"></param>  
  421.         /// <returns></returns>  
  422.         public static bool ServiceExist(string serviceName)  
  423.         {  
  424.             try  
  425.             {  
  426.                 string m_ServiceName = serviceName;  
  427.                 ServiceController[] services = ServiceController.GetServices();  
  428.                 foreach (ServiceController s in services)  
  429.                 {  
  430.                     if (s.ServiceName.ToLower() == m_ServiceName.ToLower())  
  431.                     {  
  432.                         return true;  
  433.                     }  
  434.                 }  
  435.                 return false;  
  436.             }  
  437.             catch (Exception ex)  
  438.             {  
  439.                 return false;  
  440.             }  
  441.         }  
  442. 注:手动安装window服务的方法:  
  443.   
  444. 在“Visual Studio 2005 命令提示”窗口中,运行:  
  445.   
  446. 安装服务:installutil servicepath  
  447.   
  448. 卸除服务:installutil /u servicepath  
posted @ 2011-04-21 09:56  演绎简单  阅读(2190)  评论(0编辑  收藏  举报