Windows services and worker services are not the same. Below are resources and instructions on how to create and debug a Windows service:
Steps to Create a Windows Service:
- Go to Visual Studio 2015.
- Create a new project and select Windows Service.
- Then, click Add New Item, search for Installer, and select the Installer Class. Rename it to
ProjectInstaller.cs
(if it doesn’t already exist). This class describes how the service runs, including whether it will start automatically or not.
Here is the code for the ProjectInstaller.cs
file:
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
ServiceProcessInstaller processInstaller = new ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.DisplayName = "ABPFileUploadManagerService";
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = "ABPFileUploadManagerService";
base.Installers.Add(processInstaller);
base.Installers.Add(serviceInstaller);
}
}
Configuring App Settings:
Next, go to the App Settings file and add the following configuration:
<appSettings>
<add key="LogFilePath" value="C:\Users\ASD\Desktop" />
</appSettings>
Then, write the following code into your Service.cs
file. Use System.Diagnostics.Debugger.Launch()
for debugging since we cannot run the service directly.
public partial class MyService : ServiceBase
{
private string LogFilePath = @"C:\ServiceLogs\service_log.txt";
public MyService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// System.Diagnostics.Debugger.Launch();
LogServiceStatus("Service started at " + DateTime.Now.ToString());
}
protected override void OnStop()
{
LogServiceStatus("Service stopped at " + DateTime.Now.ToString());
}
private void LogServiceStatus(string message)
{
string directory = Path.GetDirectoryName(logFilePath);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
File.AppendAllText(logFilePath, message + Environment.NewLine);
}
}
Installing and Uninstalling the Service:
Run the command prompt as Administrator. To uninstall the previous version of the service, use the following command for a 32-bit system (older services may be 32-bit and not support 64-bit):
cd "C:\Windows\Microsoft.NET\Framework\v4.0.30319"
To uninstall the previous service:
installutil.exe -u "C:\Users\ASD\Desktop\Others\abpfiledownloadmanager\ABPFileDownloadManager\ABPFileDownloadManager\bin\Debug\ABPFileDownloadManager.exe"
To install the new service:
installutil.exe "C:\Users\ASD\Desktop\Others\abpfiledownloadmanager\ABPFileDownloadManager\ABPFileDownloadManager\bin\Debug\ABPFileDownloadManager.exe"
Notes:
- Ensure the project is built and that “Prefer 32-bit” is unchecked if you are using a 64-bit system.