This guide walks you through creating a Windows service from scratch, using C# and the .NET Framework or .NET Core. You’ll learn the essential steps, from setting up the project to installing and debugging your service, so you can run background tasks automatically on Windows.
What You’ll Need
- Windows 10 or 11 (or Windows Server 2016+)
- Visual Studio 2022 (Community edition is free) or the .NET SDK
- Administrator access to install the service
- Basic familiarity with C# and command line
Step-by-Step
- Create a new project. Open Visual Studio, select Create a new project, choose Worker Service (for .NET Core) or Windows Service (for .NET Framework). Name it, e.g.,
MyService. - Add the necessary NuGet package. For .NET Core, right-click your project, select Manage NuGet Packages, and install
Microsoft.Extensions.Hosting.WindowsServices. This package provides the Windows-specific service integration. - Modify the Program.cs file. In .NET Core, change the
CreateHostBuildermethod to callUseWindowsService(). Example:public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); });For .NET Framework, the template already generates a
ServiceBasesubclass. - Implement the service logic. In the
Workerclass (or the service class), override theExecuteAsyncmethod (orOnStartandOnStopfor .NET Framework) to define what your service does. For example, write to a log file every minute. - Set the service name and description. In the
Workerclass, add the[ServiceName]attribute or set it in the project properties. For .NET Core, you can set the service name in theUseWindowsServiceoptions:.UseWindowsService(options => options.ServiceName = "MyService")
Also, add a
Descriptionattribute to the class for a friendly description in the Services console. - Build the project. Press Ctrl+Shift+B to compile. Ensure the output folder contains the executable (e.g.,
MyService.exe). - Install the service. Open a command prompt as Administrator. Navigate to the output folder (e.g.,
bin\Debug\net8.0) and run:sc create MyService binPath= "C:\path\to\MyService.exe" start= auto
Or use the
installutil.exetool for .NET Framework services:installutil MyService.exe
For .NET Core, you can also use
sc.exeor create an installer with theMicrosoft.Extensions.Hosting.WindowsServicespackage. - Start the service. Run
sc start MyServiceor open the Services app (services.msc), find your service, and click Start. - Verify it works. Check the log file or event viewer to confirm your service is running. You can also use
sc query MyServiceto see the status. - Stop and uninstall (if needed). Use
sc stop MyServiceandsc delete MyServiceto stop and remove the service.
Common Mistakes
- Forgetting to call
UseWindowsService(). Without this, the service won’t run as a Windows service; it will run as a console app. - Running the executable directly. A service must be installed and started by the Service Control Manager; double-clicking the .exe won’t work as expected.
- Not running the install command as Administrator. You’ll get an access denied error.
- Using the wrong path in
sc create. ThebinPathmust be the full absolute path to the executable, and it may need quotes if the path contains spaces. - Not handling exceptions in the service logic. If an unhandled exception occurs, the service will crash and stop.
Tips
- Use a try-catch in your service’s main loop to log errors and keep the service running.
- Set the
StartTypetoAutomaticif you want the service to start on boot. You can do this in thesc createcommand or via the Services app. - For debugging, run the service as a console app. In Visual Studio, change the output type to Console Application temporarily, or add a condition to run as console if a command-line argument like
--consoleis passed. - Use the Event Viewer to log service events. Write to the Windows event log using
EventLogclass for easier troubleshooting. - Test on a virtual machine first. This avoids messing up your main system if the service misbehaves.
Troubleshooting
- Service fails to start with error 1053. This means the service didn’t respond to the start request in time. Check your
OnStartmethod for blocking operations. Move long-running tasks to a separate thread or useExecuteAsyncproperly. - Error 193: %1 is not a valid Win32 application. This usually means you’re trying to run a .NET Core service without the correct runtime installed, or the path points to a DLL instead of the EXE. Ensure the .NET runtime is installed and the binPath points to the executable.
- Access denied when installing. Make sure you are running the command prompt as Administrator.
- Service shows as “Start Pending” and then stops. Check the Event Viewer for application errors. The service may be throwing an unhandled exception during start.
- Changes to the code don’t take effect. You must rebuild the project and then stop, uninstall, reinstall, and start the service again. Simply copying a new .exe over the old one while the service is running won’t work.
- Can’t find the service in the Services app. Make sure you used the correct service name and that the installation succeeded. Run
sc queryto list all services and grep for your name.
Frequently Asked Questions
Can I create a Windows service without Visual Studio?
Yes, you can use the .NET SDK with a text editor and the command line. The process is the same, but you’ll need to manually create the project files and build using dotnet build.
What’s the difference between a Windows service and a regular app?
A Windows service runs in the background without a user interface, starts automatically at boot (if configured), and is managed by the Service Control Manager. A regular app requires a user to log in and run it.
Can I run a Python script as a Windows service?
Yes, you can wrap a Python script in a Windows service using tools like NSSM (Non-Sucking Service Manager) or by creating a small C# wrapper that launches the Python process.
How do I debug a Windows service?
You can attach the Visual Studio debugger to the running service process, or run the service as a console app with a special argument (e.g., --console) to debug it like a normal program.
Is it possible to create a service that runs a scheduled task?
Yes, you can implement a timer inside your service to execute code at specific intervals. Alternatively, use the Windows Task Scheduler, which is often simpler for scheduled tasks.
Do I need to install .NET on the target machine?
Yes, if you use .NET Core, the target machine must have the .NET runtime installed. You can publish a self-contained deployment that includes the runtime, but that increases the size.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Mac Restart Problem? Fix the Error
- MacBook Sleep Mode: How to Turn It Off
- Oculus Air Link Not Working on Windows? Fixes
- Windows 10 Can’t Detect Hard Drive? Fixes That Work
- How to Archive Emails in Outlook Automatically or Manually
- Restore iPhone from Backup: iCloud & iTunes Steps