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 ...
随机推荐
- React Native 开发之 (01) 配置开发环境
一 React Native React Native 是由Facebook发布的开源框架,着力于提高多平台开发的开发效率 —— 仅需学习一次,编写任何平台.(Learn once, write an ...
- XMPP开发环境配置
首先配置XMPP开发环境配置需要的软件 先安装xampp-osx-1.8.3-5-installer.dmg 安装成功后launchpad里会多出一个XAMPP(其他),点开里面的manager-os ...
- [Fluent NHibernate]一对多关系处理
目录 写在前面 系列文章 一对多关系 总结 写在前面 上篇文章简单介绍了,Fluent Nhibernate使用代码的方式生成Nhibernate的配置文件,以及如何生成持久化类的映射文件.通过上篇的 ...
- Shell case esac语句
case ... esac 与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构. case 语句匹配一个值或一个模式,如果匹配成功,执行相匹配的命令.case语句格式如下: ...
- 子类可以有跟父类中同名的方法,但是会重写父类中的方法,甚至是root class中的方法
/* 子类可以重写父类中的方法,甚至是root class中的方法,比如NSObeject 的new方法,但是后提示警告如下 Method is expected to return an insta ...
- hibernate4学习
1. 安装hibernatetools插件 2. 这个是篇测试文档 来自为知笔记(Wiz)
- PHP中的魔术方法:__construct, __destruct , __call, __callStatic,__get, __set, __isset, __unset , __sleep, __wakeup, __toString, __set_state, __clone and __autoload
1.__get.__set 这两个方法是为在类和他们的父类中没有声明的属性而设计的: __get( $property ) 当调用一个未定义的属性时访问此方法: __set( $property, $ ...
- PHP如何获取Post请求中的Json字符串数据?
摘自:http://dianjingjiaoyu.blog.163.com/blog/static/18347920820114194642257/ 最近用到ext与PHP交互,ext把json数据p ...
- 《征服 C 指针》摘录5:函数形参 和 空的下标运算符[]
一.函数的形参的声明 C 语言可以像下面这样声明函数的形参: void func(int a[]) { // ... } 对于这种写法,无论怎么看都好像要向函数的参数传递数组. 可是,在 C ...
- .htaccess 基础教程(四)Apache RewriteCond 规则参数
Apache模块 mod_rewrite 提供了一个基于正则表达式分析器的重写引擎来实时重写URL请求.它支持每个完整规则可以拥有不限数量的子规则以及附加条件规则的灵活而且强大的URL操作机制.此UR ...