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. css之div等继承问题--待续

    div哪些属性是可以继承的呢? 亲测:float可以继承(错的,见下解答,),display不可以继承.有待继续学习. float不可以继承, 简单来说:浮动的元素,顾名思义,就是这个元素“浮起来”了 ...

  2. bzoj1491 社交网络

    Description 在社交网络(socialnetwork)的研究中,我们常常使用图论概念去解释一些社会现象.不妨看这样的一个问题. 在一个社交圈子里有n个人,人与人之间有不同程度的关系.我们将这 ...

  3. nyoj 106背包问题(贪心专题)

    背包问题 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 现在有很多物品(它们是可以分割的),我们知道它们每个物品的单位重量的价值v和重量w(1<=v,w< ...

  4. Javascript中闭包问题(转载)

    学习Javascript闭包(Closure)   作者: 阮一峰 日期: 2009年8月30日 闭包(closure)是Javascript语言的一个难点,也是它的特色,很多高级应用都要依靠闭包实现 ...

  5. PHP 5.4 已废弃 magic_quotes_gpc,PHP安全转义函数详解(addslashes 、htmlspecialchars、htmlentities、mysql_real_escape_string、strip_tags)

    1. addslashes() addslashes()对SQL语句中的特殊字符进行转义操作,包括(‘), (“), (), (NUL)四个字符,此函数在DBMS没有自己的转义函数时候使用,但是如果D ...

  6. Linux学习之二--搭建FTP服务器

    一.查看是否安装有FTP rpm -qa|grep vsftpd 二.如果没有安装,就安装FTP yum install -y vsftpd 三.加入开机启动 systemctl enable vsf ...

  7. Java 8之二小坑:stream parallel 和 lamada

    Stream:parallel乱序 Java 8 stream流为处理集合时非常方便.遇到的一个坑是为了提高在多核cpu下的性能,尝试了parallel().数据源是HashSet的,在做分割的时候发 ...

  8. 拖拽对DOM的影响

    前一段时间公司要对上传列表中多文本输入框添加富文本编辑功能,所以最初的想法是引入富文本编辑器插件,对每个多文本输入框实例化一次.但是上传列表还有一个可以拖拽排序的功能,在初次实例化以后,再拖拽元素就会 ...

  9. hihoCoder 1196 高斯消元·二

    Description 一个黑白网格,点一次会改变这个以及与其连通的其他方格的颜色,求最少点击次数使得所有全部变成黑色. Sol 高斯消元解异或方程组. 先建立一个方程组. \(x_i\) 表示这个点 ...

  10. ACM/ICPC 之 混合图的欧拉回路判定-网络流(POJ1637)

    //网络流判定混合图欧拉回路 //通过网络流使得各点的出入度相同则possible,否则impossible //残留网络的权值为可改变方向的次数,即n个双向边则有n次 //Time:157Ms Me ...