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 ...
随机推荐
- 深夜重温JavaScript中的对象和数组
这一块实际上已经学过了,因为没有学好,在工作过程中遇到一些对象或者数组的操作,会去百度查找,浪费了许多宝贵的时间,所以特地再拐过头来重新学习. 对象 基本概念: 对象这种基本的数据结构还有其他很多种叫 ...
- js日期格式转换
var mydate=new Date(); var year=mydate.getFullYear(); //获取四位数getYear() 获取两位 var month=mydate.getMont ...
- 【迁移】—Entity Framework实例详解 转
一.Entity Framework 迁移命令(get-help EntityFramework) Enable-Migrations 启用迁移 Add-Migration 为挂起的Model变化添加 ...
- C:Wordpress自定义文章类型(图视频)
自定义文章类型,包括: 1:单独的"文章内容模板" 2:单独的"文章列表模板" 3:单独的"控制后台"(文章分类.添加文章) 创建自定义文章 ...
- hadoop集群安装故障解决
nodemanager进程解决:http://blog.csdn.net/baiyangfu_love/article/details/13504849 编译安装:http://blog.csdn.n ...
- unix编程书中的 ourhdr.h代码
真心不知到里面写的具体什么意思,先记下吧. /*Our own header, to be included after all standard system headers*/ #ifndef _ ...
- PHP连接mysql数据库,并将取出的数据以json的格式输出
<?php error_reporting(E_ALL || ~E_NOTICE); header("Access-Control-Allow-Origin:*");//此处 ...
- JavaScript类型判断instanceof与typeof对比
经常有人会在JavaScript里写如下的方法: function checkType() { var s1 = 123; var s2 = "OK"; if (s1 instan ...
- CF100965C题解..
求方程 \[ \begin{array}\\ \sum_{i=1}^n x_i & \equiv & a_1 \pmod{p} \\ \sum_{i=1}^n x_i^2 & ...
- WebAPI返回数据类型
最近开始使用WebAPI,上手很容易,然后有些疑惑 1.WebAPI默认返回什么数据类型,json还是xml? 2.怎么修改WebAPI的返回数据类型,我用IE浏览器请求返回的数据都是JSON格式的, ...