C#操作注册服务卸载服务启动服务停止服务.. .
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Install;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text; namespace TextWindowsServers
{
/// <summary>
/// 注册服务
/// </summary>
public class RegisteredServer
{
/// <summary>
/// 它用于保存执行提交、回滚或卸载操作所需的信息。
/// </summary>
IDictionary stateSaver = new Hashtable(); private static RegisteredServer _instance = null;
private static readonly object SynObject = new object();
public static RegisteredServer Instance
{
get
{
// Syn operation.
lock (SynObject)
{
return _instance ?? (_instance = new RegisteredServer());
}
}
}
/// <summary>
/// 注册服务
/// </summary>
/// <param name="path"></param>
/// <param name="name"></param>
public void Registered(string path)
{
try
{
string name = GetServiceName(path.Trim());//通过服务路径获取服务名称
if (IsExistedService(name))//服务是否存在
{
if (ServiceIsRunning(name))//服务是否运行
{
if (!StopService(name))//停止服务
throw new Exception("停止服务出现异常");
}
UnInstallService(path, name);//卸载服务
}
InstallService(stateSaver, path, name);//安装服务
ChangeServiceStartType(, name);//改变服务类型
ServiceStart(name); //运行服务
}
catch (Exception ex)
{
//Log.Error(ex);
}
} /// <summary>
/// 获取Windows服务的名称
/// </summary>
/// <param name="serviceFileName">文件路径</param>
/// <returns>服务名称</returns>
private string GetServiceName(string serviceFileName)
{
try
{
Assembly assembly = Assembly.LoadFrom(serviceFileName);
Type[] types = assembly.GetTypes();
foreach (Type myType in types)
{
if (myType.IsClass && myType.BaseType == typeof(System.Configuration.Install.Installer))
{
FieldInfo[] fieldInfos = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Default | BindingFlags.Instance | BindingFlags.Static);
foreach (FieldInfo myFieldInfo in fieldInfos)
{
if (myFieldInfo.FieldType == typeof(System.ServiceProcess.ServiceInstaller))
{
ServiceInstaller serviceInstaller = (ServiceInstaller)myFieldInfo.GetValue(Activator.CreateInstance(myType));
return serviceInstaller.ServiceName;
}
}
}
}
return "";
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 判断服务是否存在
/// </summary>
/// <param name="serviceName"></param>
/// <returns></returns>
private bool IsExistedService(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName == serviceName)
{
return true;
}
}
return false; }
/// <summary>
/// 验证服务是否启动
/// </summary>
/// <returns></returns>
private bool ServiceIsRunning(string serviceName)
{
ServiceController service = new ServiceController(serviceName);
if (service.Status == ServiceControllerStatus.Running)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 停止服务
/// </summary>
/// <param name="serviseName"></param>
/// <returns></returns>
private bool StopService(string serviseName)
{
try
{
ServiceController service = new ServiceController(serviseName);
if (service.Status == ServiceControllerStatus.Stopped)
{
return true;
}
else
{
TimeSpan timeout = TimeSpan.FromMilliseconds( * );
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
}
}
catch
{ return false;
}
return true;
} /// <summary>
/// 卸载服务
/// </summary>
/// <param name="filepath"></param>
private void UnInstallService(string filepath, string serviceName)
{
try
{
if (IsExistedService(serviceName))
{
//UnInstall Service
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Path = filepath;
myAssemblyInstaller.Uninstall(null);
myAssemblyInstaller.Dispose();
}
}
catch (Exception ex)
{
throw new Exception("unInstallServiceError/n" + ex.Message);
}
} /// <summary>
/// 安装服务
/// </summary>
/// <param name="stateSaver"></param>
/// <param name="filepath"></param>
private void InstallService(IDictionary stateSaver, string filepath, string serviceName)
{
try
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName);
if (!IsExistedService(serviceName))
{
//Install Service
AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller();
myAssemblyInstaller.UseNewContext = true;
myAssemblyInstaller.Path = filepath;
myAssemblyInstaller.Install(stateSaver);
myAssemblyInstaller.Commit(stateSaver);
myAssemblyInstaller.Dispose();
//--Start Service
service.Start();
}
else
{
if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
{
service.Start();
}
}
}
catch (Exception ex)
{
throw new Exception("installServiceError/n" + ex.Message);
}
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName"></param>
/// <returns></returns>
private static bool ServiceStart(string serviceName)
{
try
{
ServiceController service = new ServiceController(serviceName);
if (service.Status == ServiceControllerStatus.Running)
{
return true;
}
else
{
TimeSpan timeout = TimeSpan.FromMilliseconds( * );
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
}
catch
{
return false;
}
return true;
} /// <summary>
/// 设置服务启动类型
/// 2为自动 3为手动 4 为禁用
/// </summary>
/// <param name="startType"></param>
/// <param name="serviceName"></param>
/// <returns></returns>
private static bool ChangeServiceStartType(int startType, string serviceName)
{
try
{
RegistryKey regist = Registry.LocalMachine;
RegistryKey sysReg = regist.OpenSubKey("SYSTEM");
RegistryKey currentControlSet = sysReg.OpenSubKey("CurrentControlSet");
RegistryKey services = currentControlSet.OpenSubKey("Services");
RegistryKey servicesName = services.OpenSubKey(serviceName, true);
servicesName.SetValue("Start", startType);
}
catch (Exception ex)
{ return false;
}
return true;
} }
}
C#操作注册服务卸载服务启动服务停止服务.. .的更多相关文章
- MySQL服务使用cmd启动与停止服务
MySQL未设置自动启动,在使用时需要手动打开服务,方法如下 mysql服务的启动: 以管理员的身份运行cmd命令窗口,输入命名 net start mysql 提示:必须使用管理员身份运行cmd 如 ...
- Windows Service 学习系列(二):C# windows服务:安装、卸载、启动和停止Windows Service几种方式
一.通过InstallUtil.exe安装.卸载.启动.停止Windows Service 方法一 1.以管理员身份运行cmd 2.安装windows服务 切换cd C:\Windows\Micros ...
- Centos7 redis 5.0 服务设置、启动、停止、开机启动
redis 没有配置服务,没有开启动,每次都要手工配置. 解决这个麻烦,我们new一个服务,然后开机启动即可. 1.创建服务(redis.conf 配置文件要注意,经过cp产生了很多个redis.co ...
- CentOS7 从查看、启动、停止服务说起systemctl
执行命令“systemctl status 服务名.service”可查看服务的运行状态,其中服务名后的.service 可以省略,这是CenOS7以后采用systemd作为初始化进程后产生的变化. ...
- CentOS启动和停止服务详解
服务简介Linux 系统服务是在Linux启 动时自动加载,并在Linux退出时自动停止的系统任务.在Linux 启动过程中,我们可以看得很多“starting … ”提示信息,该信息表示正在启动系统 ...
- 手把手教用C#编写Windows服务 并控制服务 安装、启动、停止、卸载
Windows服务 Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动, ...
- Windows服务BAT命令-安装、卸载、启动、停止
1.安装服务 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe D:\WiseMES\MES.WindowsService ...
- 用C#代码来安装、卸载、启动、关闭服务
/// <summary> /// 启动服务 /// </summary> /// <param name="sen ...
- C# windows服务:通过cmd命令安装、卸载、启动和停止Windows Service(InstallUtil.exe)
步骤: 1.运行--〉cmd:打开cmd命令框 2.在命令行里定位到InstallUtil.exe所在的位置 InstallUtil.exe 默认的安装位置是在C:/Windows/Microsoft ...
- 11. ZooKeeper之启动、停止服务。
转自:https://blog.csdn.net/en_joker/article/details/78673607 启动服务 首先我们来看下如何启动ZooKeeper服务.常见的启动方式有两种. J ...
随机推荐
- oracle---jdbctest--laobai
import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import ora ...
- Architectural Model - SNMP Tutorial
30.3 Architectural Model Despite the potential disadvantages, having TCP/IP management software oper ...
- Windows7微软官方原版镜像系统文件
Windows7微软官方原版镜像系统 Windows 7 是由微软公司(Microsoft)开发的操作系统,核心版本号为Windows NT 6.1.Windows 7可供家庭及 商业工作环境.笔记本 ...
- 深入了解C#系列:谈谈C#中垃圾回收与内存管理机制
今天抽空来讨论一下.Net的垃圾回收与内存管理机制,也算是完成上个<WCF分布式开发必备知识>系列后的一次休息吧.以前被别人面试的时候问过我GC工作原理的问题,我现在面试新人的时候偶尔也会 ...
- hibernate的集中持久化方法的区别
一.预备知识 在所有之前,说明一下,对于hibernate,它的对象有三种状态,transient.persistent.detached 下边是常见的翻译办法: transient:瞬态或者自由态 ...
- 探索ASP.NET MVC框架之路由系统
引言 对于ASP.NET MVC的路由系统相信大家肯定不陌生.今天我们就深入ASP.NET的框架内部来看一下路由系统到底是怎么通过我们给出的地址(例如:/Home/Index)解析出Controlle ...
- 进入OS前的两步之PendSV(任务切换)
先了解下如何使用PendSV异常.(为何要使用PendSV而不是其他的异常,请参考<cortex-M3权威指南>) 1,如何设定PendSV优先级? NVIC_SYSPRI14 EQU 0 ...
- Linux下百度云盘报 获取bdstoken失败
在用linux下百度云盘工具(bcloud),登录时,报获取bdstoken失败. 在网上搜了一下,解决办法如下. 找到auth.py文件 locate auth.py |grep bcloud 结果 ...
- [转]Oracle存在则更新,不存在则插入
原文:http://hi.baidu.com/mawf2008/item/eec8c7ad1c5be5ae29ce9da6 merge into a using bon (a.a=b.b)when m ...
- unity3D游戏-WorldFight
计划写一个2D策略类的游戏,玩法类似炉石传说,以收集卡牌为主,不同的地方在于战斗方式类似棋类游戏,而且还有一个技能系统作为补充. ---更新(2015.7.13) v2.0.1更新: 添加了基本AI ...