C# windows服务:

第一种 :通过cmd命令安装、卸载、启动和停止Windows Service(InstallUtil.exe)

步骤:

1。运行--〉cmd:打开cmd命令框

2。在命令行里定位到InstallUtil.exe所在的位置

InstallUtil.exe 默认的安装位置是在C:/Windows/Microsoft.NET/Framework/v2.0.50727里面,所以你要在cmd里通过cd定位到该位置(cd C:/Windows/Microsoft.NET/Framework/v2.0.50727)

3。操作命令:

1). 安装服务命令:在命令行里输入下面的命令:

InstallUtil.exe Path/WinServiceName.exe

其中Path表示ServiceName.exe所在的位置,回车即可

2). 启动服务命令

net start ServiceName

ServiceName是真正的Service的名称(ServiceBase.ServiceName),跟.exe的名称可能一样,也可能不一样。如果不清楚,就到已安装的服务里面找到你的服务,右键属性里面看服务名称

3). 停止服务命令

net stop ServiceName

4). 卸载服务命令:在命令行里输入下面的命令:

InstallUtil.exe /u Path/WinServiceName.exe

其中Path表示ServiceName.exe所在的位置,回车即可

使用VS调用InstallUtil.exe工具,输入参数:
安装:D:\GCAMS\Code\PublicClass\SaveLogWindowsService\bin\Debug\SaveLogWindowsService.exe

启动:cmd--》net start ServiceName或者打开服务管理界面,选择需要启动的服务,右击启动服务

卸载:/U D:\GCAMS\Code\PublicClass\SaveLogWindowsService\bin\Debug\SaveLogWindowsService.exe

创建安装bat文件

安装Socket服务(Server).bat

@echo on
color 2f
mode con: cols=80 lines=25
echo 请按任意键开始安装SocketServer后台服务...
pause
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe SocketWindowsService.exe
rem net start SocketServer
sc start SocketServer %1
pause

创建安装bat文件

卸载Socket服务(Server).bat

@echo on
color 2f
mode con: cols=80 lines=25
echo 请按任意键开始卸载SocketServer后台服务...
pause
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe -u SocketWindowsService.exe
pause

  

第二种:使用WindowsServiceHelper类进行安装

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceProcess;
using System.Collections;
using Microsoft.Win32;
using System.Configuration.Install; namespace OperationWinService
{
public static class WindowsServiceHelper
{
#region 已封装Window服务
private static string ServerName = ConfigurationManager.AppSettings["WinServiceName"].ToString();
private static string ExecuteName = ConfigurationManager.AppSettings["ExecuteName"].ToString();
/// <summary>
/// 安装服务
/// </summary>
/// <param name="NameService">Windows服务显示名称</param>
/// <returns>存在返回 true,否则返回 false;</returns>
public static bool InstallService()
{
bool flag = false;
if (!IsServiceIsExisted())
{
try
{
string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
string serviceFileName = location.Substring(, location.LastIndexOf('\\') + ) + ExecuteName + ".exe"; //测试用的绝对路径
//string serviceFileName = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe";
InstallMyService(null, serviceFileName);
flag = true;
}
catch(Exception ex)
{
flag = false;
LogHelper.WriteLog(typeof(WindowsServiceHelper), "InstallService执行错误:" + ex.Message); } }
else
{
flag = true;
LogHelper.WriteLog(typeof(WindowsServiceHelper), "InstallService执行配置服务名称不存在");
}
return flag;
} /// <summary>
/// 卸载服务
/// </summary>
/// <param name="NameService">Windows服务显示名称</param>
/// <returns>存在返回 true,否则返回 false;</returns>
public static bool UninstallService()
{
bool flag = false;
if (IsServiceIsExisted())
{
try
{
string location = System.Reflection.Assembly.GetExecutingAssembly().Location;
string serviceFileName = location.Substring(, location.LastIndexOf('\\') + ) + ExecuteName + ".exe";
//测试用的绝对路径
//string serviceFileName = @"F:\CM.WebSite\KJLMDemo\bin\Debug\KJLMDemo.exe";
UnInstallMyService(serviceFileName);
flag = true;
}
catch (Exception ex)
{
flag = false;
LogHelper.WriteLog(typeof(WindowsServiceHelper), "UninstallService执行错误:" + ex.Message);
}
}
else
{
flag = true;
LogHelper.WriteLog(typeof(WindowsServiceHelper), "UninstallService执行配置服务名称不存在");
}
return flag;
} /// <summary>
/// 检查Windows服务是否存在
/// </summary>
/// <param name="NameService">Windows服务显示名称</param>
/// <returns>存在返回 true,否则返回 false;</returns>
public static bool IsServiceIsExisted()
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController s in services)
{
if (s.ServiceName.ToLower() == ServerName.ToLower())
{
return true;
}
}
return false;
} /// <summary>
/// 安装Windows服务
/// </summary>
/// <param name="stateSaver">集合</param>
/// <param name="filepath">Windows服务程序文件路径</param>
private static void InstallMyService(IDictionary stateSaver, string filePath)
{
AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
AssemblyInstaller1.UseNewContext = true;
AssemblyInstaller1.Path = filePath;
AssemblyInstaller1.Install(stateSaver);
AssemblyInstaller1.Commit(stateSaver);
AssemblyInstaller1.Dispose();
} /// <summary>
/// 卸载Windows服务
/// </summary>
/// <param name="filePath">Windows服务程序文件路径</param>
private static void UnInstallMyService(string filePath)
{
AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();
AssemblyInstaller1.UseNewContext = true;
AssemblyInstaller1.Path = filePath;
AssemblyInstaller1.Uninstall(null);
AssemblyInstaller1.Dispose();
} /// <summary>
/// 判断某个Windows服务是否启动
/// </summary>
/// <param name="serviceName">Windows服务显示名称</param>
/// <returns>bool</returns>
public static bool IsServiceStart()
{
bool bStartStatus = false; ServiceController psc = new ServiceController(ServerName); try
{
if (!psc.Status.Equals(ServiceControllerStatus.Stopped))
{
bStartStatus = true;
} return bStartStatus;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
} } /// <summary>
/// 修改服务的启动项 2为自动,3为手动
/// </summary>
/// <param name="startType">2为自动,3为手动</param>
/// <param name="serviceName">Windows服务显示名称</param>
/// <returns>bool</returns>
public 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; } /// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName">Windows服务显示名称</param>
/// <returns>bool</returns>
public static bool StartService()
{
bool flag = true;
try
{
if (IsServiceIsExisted())
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(ServerName);
if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending)
{
service.Start();
for (int i = ; i < ; i++)
{
service.Refresh();
System.Threading.Thread.Sleep();
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
break;
}
if (i == )
{
flag = false;
}
}
}
}
else
{
flag = false;
}
}
catch(Exception ex)
{
LogHelper.WriteLog(typeof(WindowsServiceHelper), "StartService执行错误:" + ex.Message);
}
return flag;
} /// <summary>
/// 停止服务
/// </summary>
/// <param name="serviceName">Windows服务显示名称</param>
/// <returns>bool</returns>
public static bool StopService()
{
bool flag = true;
try
{
if (IsServiceIsExisted())
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(ServerName);
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
{
service.Stop();
for (int i = ; i < ; i++)
{
service.Refresh();
System.Threading.Thread.Sleep();
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
{
break;
}
if (i == )
{
flag = false;
}
}
}
}
else
{
flag = false;
}
}
catch(Exception ex)
{
LogHelper.WriteLog(typeof(WindowsServiceHelper), "StopService执行错误:" + ex.Message);
}
return flag;
}
#endregion
}
}

c# 安装windows服务的更多相关文章

  1. 安装windows服务批处理代码

    批处理是DOS时代比较常用的方法之一,目前来说也是一种高效的方法,复制代码到文本文件中,保存并修改文件扩展名为“*.bat”. 安装windows服务批处理代码如下: @echo off set fi ...

  2. 无法从命令行或调试器启动服务,必须首先安装Windows服务(使用installutil.exe),然后用ServerExplorer、Windows服务器管理工具或NET START命令启动它

    无法从命令行或调试器启动服务,必须首先安装Windows服务(使用installutil.exe),然后用ServerExplorer.Windows服务器管理工具或NET START命令启动它 1. ...

  3. .net安装windows服务配置文件config

    .net安装windows服务 : 在windows服务的项目(WindowsService1)代码文件中有一个app.config 配置文件,可以通过此文件进行时间等的更改而无需重新生成项目:那我们 ...

  4. .net安装windows服务和生产webservice

    安装windows服务 1.打开cmd对话框. 2.输入 cd WINDOWS\Microsoft.NET\Framework64\v2.0.50727\ 3.回车 4.输入InstallUtil.e ...

  5. TopSelf安装Windows服务提示:执行未经授权的操作。。

    在一个项目中用到了八九个服务,服务的执行时间也是五花八门,有的年末执行一次,有的月中执行一次,有的月末最后一天执行一次,有的月初连续执行5天, 有的每天晚上执行,...还好各个服务并没有严格的关联关系 ...

  6. mysql下载和安装Windows服务

    一.下载mysql:https://dev.mysql.com/downloads/mysql/,解压拷贝到D:\software\mysql-8.0.13-winx64 二.在D:\software ...

  7. 【C#】安装windows服务

    参考:http://blog.csdn.net ,http://blog.csdn.net/dyzcode 1.新建 visual studio insaller 项目2.添加 [文件系统]3.添加 ...

  8. 批处理安装Windows服务,提示"InstallUtil.exe"不是内部命令也不是外部命令解决方式

    今天在测试一个C#写的windows服务的时候,在用bat进行调用cmd安装的时候, cd C:\Windows\Microsoft.NET\Framework\v2.0.50727 InstallU ...

  9. MongoDB安装Windows服务

    由于官方下载较慢.这里提供一个个人百度共享网盘地址: http://pan.baidu.com/s/1mhHW0nI mongodb-win32-x86_64-3.2.3 使用以下命令将MongoDB ...

随机推荐

  1. Android Material Design 5.0 PickerDialog

    5.0系统下的时间选择器效果图: 该项目兼容到3.0下面所以用第三方开源项目:actionbarsherlock,动画效果兼容:nineoldandroids-2.4.0.jar,格式转换器:joda ...

  2. 从Handler+Message+Looper源代码带你分析Android系统的消息处理机制

    PS一句:不得不说CSDN同步做的非常烂.还得我花了近1个小时恢复这篇博客. 引言 [转载请注明出处:http://blog.csdn.net/feiduclear_up CSDN 废墟的树] 作为A ...

  3. <a href='javacript:' title='{$str}'>是什么意思(多看学习视频)

    <a href='javacript:' title='{$str}'>是什么意思(多看学习视频) 一.总结 一句话总结: 1.javascript:是什么? 伪协议,后面接javascr ...

  4. Oracle 11g对依赖的推断达到字段级

    在Oracle 10g下,推断依赖性仅仅达到了对象级.也就是说存储过程訪问的对象一旦发生了变化.那么Oracle就会将存储过程置为INVALID状态.所以在为表做了DDL操作后.须要把存储过程又一次进 ...

  5. Oracle数据库的基本概念(转)

    一.数据库 我们在安装Oracle数据库时,全局数据库名:就是一个数据库的标识,在安装时就要想好,以后一般不修改,修改起来也麻烦,因为数据库一旦安装,数据库名就写进了控制文件,数据库表,很多地方都会用 ...

  6. [GeekBand] C++继承关系下虚函数内存分布

    本文参考文献:GeekBand课堂内容,授课老师:侯捷 :深度探索C++对象模型(侯捷译) :网络资料,如:http://blog.csdn.net/sanfengshou/article/detai ...

  7. 【序列操作I】线段树

    题目描述 Lxhgww 最近收到了一个 01 序列,序列里面包含了 n(1≤n≤105)个数,这些书要么是 0,要么是 1,现在对这个序列有五种变换操作和询问操作:1. 0 a b ,把[a,b]区间 ...

  8. 【9302】&&【a301】兔子繁殖

    Time Limit: 10 second Memory Limit: 2 MB 问题描述 有一种兔子,出生后一个月就可以长大,然后再过一个月一对长大的兔子就可以生育一对小兔子且以后每个月都能生育一对 ...

  9. error: openssl/md5.h: No such file or directory

    出现:error: openssl/md5.h: No such file or directory 原因是openssl-devel没有安装,运行: yum install libssl-dev 就 ...

  10. Struts2——(3)ValueStack(值栈)

    一.ValueStack 主要用于存储请求相关信息,内部结构如下 root区:被称为根存储区,是一个栈结构,栈顶元素为当前请求的Action对象. context区:被称为变量存储区,是一个Map结构 ...