Introduction
Creating a Windows Service in .NET Core involves several steps. Here’s a step-by-step guide to help you create a Windows Service using .NET Core:
Step 1: Create a .NET Core Console Application
- Open a terminal or command prompt.
- Navigate to the directory where you want to create your project.
- Run the following command to create a new .NET Core Console Application:
dotnet new console -n MyWindowsService
- Navigate into the newly created project directory:
cd MyWindowsService
Step 2: Modify the Program.cs File
- Open the
Program.cs
file in your preferred code editor. - Replace the content with the following code:
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
namespace MyWindowsService
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
RunAsConsole();
}
else
{
RunAsService();
}
}
private static void RunAsConsole()
{
// Your console application logic goes here.
Console.WriteLine("Press Ctrl+C to exit.");
Thread.Sleep(Timeout.Infinite);
}
private static void RunAsService()
{
ServiceBase.Run(new ServiceBase[]
{
new MyService()
});
}
}
class MyService : ServiceBase
{
private readonly ManualResetEvent _shutdownEvent = new ManualResetEvent(false);
protected override void OnStart(string[] args)
{
// Your service startup logic goes here.
Console.WriteLine("Service started.");
}
protected override void OnStop()
{
// Your service stop logic goes here.
Console.WriteLine("Service stopped.");
_shutdownEvent.Set();
}
}
}
Step 3: Install the System.ServiceProcess
Package
- In the terminal, navigate to the project directory (
MyWindowsService
). - Run the following command to install the
System.ServiceProcess
package:
dotnet add package System.ServiceProcess
Step 4: Build and Install the Service
- Build the project by running the following command:
dotnet build
- Install the service using the
sc
command-line tool (requires administrator privileges):
sc create MyWindowsService binPath= "path\to\MyWindowsService.exe"
Replace "path\to\MyWindowsService.exe"
with the actual path to your compiled executable.
Step 5: Start and Manage the Service
- Start the service using the
sc
command:
sc start MyWindowsService
- Stop the service using the
sc
command:
sc stop MyWindowsService
- View the service status:
sc query MyWindowsService
Congratulations! You’ve created a basic Windows Service using .NET Core. You can customize the MyService
class with your specific logic for the service’s behavior. Remember that the provided example is minimal; you can add error handling, logging, and more sophisticated features as needed.