2009-12-12 84 views
0

如何在c#.net中注册Windows服务?如何注册winservice?

+0

http://stackoverflow.com/questions/208575 /你怎么注册一个windows-service-installation- – nayakam 2009-12-12 13:53:15

+0

我想在运行时做到这一点。 ,我想知道服务是否注册过。 – Behrooz 2009-12-12 13:57:21

回答

0

这里(Easiest language to create a windows service)是在C#中创建Windows服务的分步说明。步骤6-9显示如何准备您的服务以在本地机器上注册。第9步讨论如何使用InstallUtil.exe安装您的服务。

更进一步,您可以参考此处的分步说明(How to make a .NET Windows Service start right after the installation?),以使Windows服务从命令行自行安装,即不必使用InstallUtil.exe。例如,要安装该服务,你会使用这个

MyService.exe /install 

要卸载,你应该这样做

MyService.exe /uninstall 
+0

第二个环节解决了这个问题。 – Behrooz 2009-12-15 12:12:22

0

有几种方法。这取决于上下文:

1)您可以创建一个Windows安装程序包来执行此操作以进行生产。我相信Visual Studio安装项目会这样做。

2)对于开发,installutil.exe应该这样做,因为Svetlozar Angelov已经说过。

3)如果您确实需要以某种方式自定义安装,您可以编写自己的.NET代码来完成它。看看System.ServiceProcess.ServiceInstaller课程。

1

要找出是否已经安装了服务,获得已安装的服务列表,看看,如果你是在它:

bool existsAlready = System.ServiceProcess.ServiceController.GetServices() 
    .Where(service => service.ServiceName == yourServiceName) 
    .Any(); 

实际安装它,你必须创建一个安装程序对象并告诉它你的可执行文件和服务名称。喜欢的东西:

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()); 

这或多或少所有InstallUtil.exe如果你这样做,是记录的方式会与你的班。

要启动或停止服务,请使用ServiceController类。