网上看了这个大神的帖子,以为很简单,自己也想试一下,结果问题多多
https://www.cnblogs.com/cncc/p/7170951.html
第一个问题便是:代码抄过来后发现这两句出问题,没办法引用,百度了半天都很麻烦,度娘折腾半天也没方案,后来想以下,说不定nuget有呢,果然试一下就ok了,直接搜索System.ServiceProcess/Configuration即可搞定
using System.ServiceProcess;
using System.Configuration.Install;
第二个问题是:搞定了代码问题,终于可以跑起来了,发现没办法安装服务
大家都知道,windows7/10有时候问题莫名其妙,就用管理员权限试一下,果然发现,必须用管理员权限运行,就可以安装,但是仍然无法启动服务
第三个问题:服务安装了,但是仍然没办法启动,停止服务,也没办法卸载服务。
用管理员运行问题依旧,百度到这个大神https://blog.csdn.net/csethcrm/article/details/17922397,果然,把服务程序的目录安全,添加一个everyone用户,权限设置为完全控制,所有终于搞定了。
using System; using System.Collections; using System.Collections.Generic; using System.Configuration.Install; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace WindowsService1 { public class ServiceManager { //判断服务是否存在 public static bool IsServiceExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController sc in services) { if (sc.ServiceName.ToLower() == serviceName.ToLower()) { return true; } } return false; } //安装服务 public static void InstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; IDictionary savedState = new Hashtable(); installer.Install(savedState); installer.Commit(savedState); } } //卸载服务 public static void UninstallService(string serviceFilePath) { using (AssemblyInstaller installer = new AssemblyInstaller()) { installer.UseNewContext = true; installer.Path = serviceFilePath; installer.Uninstall(null); } } //启动服务 public static void ServiceStart(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Stopped) { control.Start(); } } } //停止服务 public static void ServiceStop(string serviceName) { using (ServiceController control = new ServiceController(serviceName)) { if (control.Status == ServiceControllerStatus.Running) { control.Stop(); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; namespace WindowsService1 { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } string filePath = $@"C:\Users\xxx\Desktop\Temp\WindowsFormsApp4\WindowsFormsApp4\bin\Debug\MyServiceLog.txt"; protected override void OnStart(string[] args) { using (FileStream stream = new FileStream(filePath, FileMode.Append)) { using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine($"{DateTime.Now},服务启动!"); } } } protected override void OnStop() { // TODO: 在此处添加代码以执行停止服务所需的关闭操作。 using (FileStream stream = new FileStream(filePath, FileMode.Append)) { using (StreamWriter writer = new StreamWriter(stream)) { writer.WriteLine($"{DateTime.Now},服务停止!"); } } } } }