How can I register a winservice?
How can I开发者_StackOverflow社区 register a windows service within c#.net?
Have a look at these
- Creating a Basic Windows Service in C#
- Creating a Windows Service with C#
- Creating a Windows Service in C#
To find out if the service is already installed, get the list of services that are installed, and see if yours is in it:
bool existsAlready = System.ServiceProcess.ServiceController.GetServices()
.Where(service => service.ServiceName == yourServiceName)
.Any();
To actually install it, you have to create an installer object and tell it your executable and service name. Something like:
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller
{
Account = ServiceAccount.LocalService
};
string executablePath = String.Format("/assemblypath={0}", "yourprogram.exe"));
InstallContext context = new InstallContext(null, new[] { executablePath });
var installer = new ServiceInstaller
{
Context = context,
DisplayName = yourServiceName,
Description = yourServiceName,
ServiceName = yourServiceName,
StartType = ServiceStartMode.Automatic,
Parent = serviceProcessInstaller,
};
installer.Install(new System.Collections.Specialized.ListDictionary());
This is more or less all that InstallUtil.exe would do with your classes if you did it the documented way.
To start or stop a service, use the ServiceController class.
Have a look at Writting Windows Service
Here (Easiest language to create a windows service) is a step-by-step set of instructions for creating a Windows service in C#. Steps 6-9 show how to prepare your service to be registered with the local machine. Step 9 discusses how to use InstallUtil.exe
to install your service.
To take it a step further, you can refer to the step-by-step instructions here (How to make a .NET Windows Service start right after the installation?) in order to have your Windows service install itself from the command line, i.e., without having to use InstallUtil.exe
. For example, to install the service, you'd use this
MyService.exe /install
To uninstall, you'd do this
MyService.exe /uninstall
How do you register a Windows Service during installation? question tells us about this great step-by-step tutorial:
Walkthrough: Creating a Windows Service Application in the Component Designer.
There are several ways. It depends on the context:
1) You can create a Windows Installer package to do this for production. I believe a Visual Studio setup project will do this.
2) For development, installutil.exe should do it, as Svetlozar Angelov already said.
3) If you really need to customise the installation somehow you can write your own .NET code to do it. Look at the System.ServiceProcess.ServiceInstaller
class.
精彩评论