在NuGet中的包管理中添加两个包
System.ServiceProcess.ServiceController
Microsoft.Extensions.Hosting.WindowsServices
在Program.cs中添加.UseWindowsService(),另外还需要设置管理员身份运行
Program.cs代码如下
cs
public class Program
{
public static void Main(string[] args)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator)) //必须是管理员身份运行
{
CreateHostBuilder(args).Build().Run();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args).UseWindowsService()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
以上步骤完成后,就可以通过以下几种方式启动这个Windows服务
- 通过CMD命令启动
- 通过一个.exe应用程序启动这个服务
cs
1.CMD找到用于系统自动的用于启动Windows服务的工具
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
2.目录为你需要启动的Windows服务的程序(此命令是为了安装服务)
InstallUtil.exe "D:\Process.Manage.Service\bin\Debug\Process.Manage.Service.exe"
3.启动这个服务(MyServive为服务名称)
net start MyServive
4.停止服务(如果需要停止)
net stop MyServive
5.卸载服务(如果需要卸载)
InstallUtil.exe /u "D:\Process.Manage.Service\bin\Debug\Process.Manage.Service.exe"
以下列出的是通过创建一个.exe应用程序,让后把这个应用程序放在.net Core程序目录中即可,下面是启动服务的详细代码
cs
using System;
using System.Collections;
using System.Configuration.Install;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Threading;
namespace Install
{
internal class Program
{
private static readonly string ServiceName = "Service";
private static readonly string ServicePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Service.exe");
private static void Consoler(string message)
{
string date = System.DateTime.Now.ToString("HH:mm:ss,fff");
System.Console.WriteLine($"{date} {message}");
}
static void Main(string[] args)
{
try
{
if (IsExist(ServiceName))
{
Consoler($"检测到服务已安装。{ServicePath}");
}
else if (File.Exists(ServicePath))
{
//InstallService(ServicePath);
Install(ServicePath);
}
else
{
throw new Exception($"指定文件不存在。{ServicePath}");
}
StartService(ServiceName);
Consoler("操作已成功完成,3秒后窗口自动关闭......");
Thread.Sleep(3000);
}
catch (Exception ex)
{
Consoler($"服务安装失败!Error:{ex.Message}");
Console.ReadKey(true);
}
}
private static void Install(string servicePath)
{
try
{
string createCommand = $"sc create \"{ServiceName}\" binPath= \"{servicePath}\" start= auto obj= \"LocalSystem\"";
ExecuteCommand(createCommand);
}
catch (Exception err)
{
Console.WriteLine(err.Message);
}
}
private static void ExecuteCommand(string command)
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c {command}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (Process process = new Process())
{
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
}
}
/// <summary>
/// 安装服务
/// </summary>
/// <param name="servicePath"></param>
private static void InstallService(string servicePath)
{
try
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = servicePath;
IDictionary savedState = new Hashtable();
installer.Install(savedState);
installer.Commit(savedState);
Consoler("安装服务成功");
}
}
catch (Exception err)
{
Consoler(err.Message);
}
}
/// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName"></param>
private static void StartService(string serviceName)
{
using (ServiceController service = new ServiceController(serviceName))
{
if (service.Status != ServiceControllerStatus.Running)
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(3));
}
Consoler("服务启动成功");
}
}
private static bool IsExist(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
var list = services.Select(s => s.ServiceName).ToList();
foreach (ServiceController sc in services)
{
if (sc.ServiceName.ToLower() == serviceName.ToLower())
{
return true;
}
}
return false;
}
}
}