C# ---- 创建Windows服务及安装、启动、卸载服务、服务定时运行
创建Windows服务
打开VS创建Windows服务
1、打开Service1.cs文件右键点添加安装程序,会生成一个ProjectInstaller.cs安装文件
2、打开ProjectInstaller.cs文件选中serviceProcessInstaller1右键属性设置Account为LocalSystem,在选中serviceInstaller1右键属性设置ServiceName(服务名称),设置StartType为Automatic(自动启动)
3、打开Service1.cs右键查看代码会看到如下几个方法:
/// <summary>
/// 服务启动方法
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
LogHelper.WriteLog("xxx系统服务:【服务启动】");
}
/// <summary>
/// 停止服务方法
/// </summary>
protected override void OnStop()
{
LogHelper.WriteLog("xxx系统服务:【服务停止】");
}
/// <summary>
/// 计算机关闭方法
/// </summary>
protected override void OnShutdown()
{
LogHelper.WriteLog("xxx系统服务:【计算机关闭】");
}
下面我们创建一个计时器来定时运行服务,代码如下:
在构造函数里面定义Timer
public Service1()
{
InitializeComponent();
Timer timer = new Timer();
timer.Elapsed += new ElapsedEventHandler(TimedEvent); //定时运行事件
timer.Interval = 5000;//每5秒执行一次
timer.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
timer.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
}
//定时执行事件
private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
//具体业务逻辑
Timer time = (Timer)sender;
try
{
time.Enabled = false;
LogHelper.WriteLog(" 服务运行...");
// TODO 这里写需要实现功能
}
catch (Exception ex)
{
LogHelper.WriteLog(ex.Message);
}
finally
{
time.Enabled = true;
}
}
实现安装、启动、停止、卸载服务
新建一个WPF或者Winform程序,直接上代码
1、前端界面如下
<UniformGrid Columns = "4" >
<Button Content="安装服务" Name="btnInstallService" VerticalAlignment="Center" Margin="10" Height="30" Width="100" Click="btnInstallService_Click"/>
<Button Content = "启动服务" Name="btnStartService" VerticalAlignment="Center" Margin="10" Height="30" Width="100" Click="btnStartService_Click"/>
<Button Content = "停止服务" Name="btnStopService" VerticalAlignment="Center" Margin="10" Height="30" Width="100" Click="btnStopService_Click"/>
<Button Content = "卸载服务" Name="btnUninstallService" VerticalAlignment="Center" Margin="10" Height="30" Width="100" Click="btnUninstallService_Click"/>
</UniformGrid>
2、后台代码如下:
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
//TODO 找到Debug下面的服务安装文件
string serviceFilePath = System.AppDomain.CurrentDomain.BaseDirectory + "CodeNumBerTXT_Service.exe";
//TODO 服务名称
string serviceName = "CreateTXTService";
public MainWindow()
{
InitializeComponent();
}
//判断服务是否存在
private bool isServiceExisted(string serviceName)
{
try
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController sc in services)
{
if (sc.ServiceName.ToLower() == serviceName.ToLower())
{
return true;
}
}
return false;
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
return false;
}
}
//安装服务
private void InstallService(string serviceFilePath)
{
try
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
IDictionary savedState = new Hashtable();
installer.Install(savedState);
installer.Commit(savedState);
StartService(serviceName);
MessageBox.Show("安装服务成功!");
}
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
//卸载服务
private void UninstallService(string serviceFilePath)
{
try
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
installer.Uninstall(null);
MessageBox.Show("卸载服务成功!");
}
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
}
//启动服务
private void StartService(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Stopped)
{
control.Start();
}
}
}
//停止服务
private void StopService(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Running)
{
control.Stop();
MessageBox.Show("停止服务成功!");
}
}
}
private void btnInstallService_Click(object sender, RoutedEventArgs e)
{
if (this.isServiceExisted(serviceName)) this.UninstallService(serviceName);
this.InstallService(serviceFilePath);
}
private void btnStartService_Click(object sender, RoutedEventArgs e)
{
if (this.isServiceExisted(serviceName)) this.StartService(serviceName);
}
private void btnStopService_Click(object sender, RoutedEventArgs e)
{
if (this.isServiceExisted(serviceName)) this.StopService(serviceName);
}
private void btnUninstallService_Click(object sender, RoutedEventArgs e)
{
if (this.isServiceExisted(serviceName))
{
this.StopService(serviceName);
this.UninstallService(serviceFilePath);
}
}
}
--------------end