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#操作注册服务卸载服务启动服务停止服务.. .

C#操作注册服务卸载服务启动服务停止服务.. .的更多相关文章

  1. MySQL服务使用cmd启动与停止服务

    MySQL未设置自动启动,在使用时需要手动打开服务,方法如下 mysql服务的启动: 以管理员的身份运行cmd命令窗口,输入命名 net start mysql 提示:必须使用管理员身份运行cmd 如 ...

  2. Windows Service 学习系列(二):C# windows服务:安装、卸载、启动和停止Windows Service几种方式

    一.通过InstallUtil.exe安装.卸载.启动.停止Windows Service 方法一 1.以管理员身份运行cmd 2.安装windows服务 切换cd C:\Windows\Micros ...

  3. Centos7 redis 5.0 服务设置、启动、停止、开机启动

    redis 没有配置服务,没有开启动,每次都要手工配置. 解决这个麻烦,我们new一个服务,然后开机启动即可. 1.创建服务(redis.conf 配置文件要注意,经过cp产生了很多个redis.co ...

  4. CentOS7 从查看、启动、停止服务说起systemctl

    执行命令“systemctl status 服务名.service”可查看服务的运行状态,其中服务名后的.service 可以省略,这是CenOS7以后采用systemd作为初始化进程后产生的变化. ...

  5. CentOS启动和停止服务详解

    服务简介Linux 系统服务是在Linux启 动时自动加载,并在Linux退出时自动停止的系统任务.在Linux 启动过程中,我们可以看得很多“starting … ”提示信息,该信息表示正在启动系统 ...

  6. 手把手教用C#编写Windows服务 并控制服务 安装、启动、停止、卸载

    Windows服务 Microsoft Windows 服务(即,以前的 NT 服务)使您能够创建在它们自己的 Windows 会话中可长时间运行的可执行应用程序.这些服务可以在计算机启动时自动启动, ...

  7. Windows服务BAT命令-安装、卸载、启动、停止

    1.安装服务 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe D:\WiseMES\MES.WindowsService ...

  8. 用C#代码来安装、卸载、启动、关闭服务

    /// <summary>        /// 启动服务         /// </summary>        /// <param name="sen ...

  9. C# windows服务:通过cmd命令安装、卸载、启动和停止Windows Service(InstallUtil.exe)

    步骤: 1.运行--〉cmd:打开cmd命令框 2.在命令行里定位到InstallUtil.exe所在的位置 InstallUtil.exe 默认的安装位置是在C:/Windows/Microsoft ...

  10. 11. ZooKeeper之启动、停止服务。

    转自:https://blog.csdn.net/en_joker/article/details/78673607 启动服务 首先我们来看下如何启动ZooKeeper服务.常见的启动方式有两种. J ...

随机推荐

  1. 加载未安装APK中的类

    一.前提 目的:动态加载SD卡中Apk的类. 注意:被加载的APK是未安装的. 相关:本文是本博另外一篇文章:Android动态加载jar/dex的升级版. 截图: 成功截图: 二.准备 准备被调用A ...

  2. 如何阅读Java源码 阅读java的真实体会

    刚才在论坛不经意间,看到有关源码阅读的帖子.回想自己前几年,阅读源码那种兴奋和成就感(1),不禁又有一种激动. 源码阅读,我觉得最核心有三点:技术基础+强烈的求知欲+耐心.   说到技术基础,我打个比 ...

  3. thinkphp 后台权限列表

    核心代码: // 检测用户权限权限 public function admin_priv($action){ $action_list = session('user.action_list'); i ...

  4. .net 开源工作流比较及应用

    送上比较内容图: 鉴于这个表的内容,与公司技术与需求的结合,我们选择啦RoadFlow工作流引擎. 下面踏上RoadFlow的征程. RoadFlow的下载.部署.及使用 官方网址:http://cq ...

  5. 关于Hibernate5.x的那点事

    1.如果采用程序建表: 4.x版本: Configuration cfg = new Configuration().configure(); SchemaExport se = new Schema ...

  6. Linux下如何不停止服务,清空nohup.out文件

    tips:最近发现有不少人在百度这个问题,当初如易我也是初学者,随便从网上搜了一下,就转过来了,不过为了避免搜索结果同质化,为大家提供更翔实的参考,我将nohup.out相关知识整理汇总如下: 1.n ...

  7. 1.0、Struts2的简单搭建方法

    一.Struts2:是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet:用于jsp页面与Java代码之间的交互. 1.核心:Filter拦截器,对所有的请求进行拦截. 2.工作 ...

  8. IOS系统基础知识

    在iOS应用中,每个程序得main函数中都调用了UIApplicationMain函数. 1 2 3 4 5 6 int main(int argc, char *argv[])  {      @a ...

  9. UVA-11991 Easy Problem from Rujia Liu?

    Problem E Easy Problem from Rujia Liu? Though Rujia Liu usually sets hard problems for contests (for ...

  10. Github.com上有哪些比较有趣的PHP项目?

    链接就不贴了,可以在github上进行搜索.这里就不列举 symfony.laravel 这些大家都知道的项目了.只列举比较有意思的. swoole, C扩展实现的PHP异步并行网络通信框架,可以重新 ...