为 .NET Windows 服务添加描述






4.71/5 (54投票s)
2002年2月7日
1分钟阅读

329603

1782
本文档描述了如何为您的 .NET Framework Windows 服务添加描述,以便在“服务”管理工具中显示。
引言
尽管 .NET Framework 通过 System.ServiceProcess 命名空间下的类提供了极其强大的 Windows 服务支持,但出于某种原因,省略了为服务指定在“服务”控制面板小程序/MMC 管理单元中显示的描述的功能。 存在一个名为 ServiceProcessDescription 的属性类,但它实际上指定了 Services MMC 在名称列中显示的内容,而描述列仍然为空。 本文将引导您完成一个低级技巧,通过直接将其添加到服务的注册表项来添加描述。大多数服务将其配置信息保存在注册表中,位于 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\
//This code should be inserted into your ProjectInstaller class' code
public override void Install(IDictionary stateServer)
{
Microsoft.Win32.RegistryKey system,
//HKEY_LOCAL_MACHINE\Services\CurrentControlSet
currentControlSet,
//...\Services
services,
//...\<Service Name>
service,
//...\Parameters - this is where you can put service-specific configuration
config;
try
{
//Let the project installer do its job
base.Install(stateServer);
//Open the HKEY_LOCAL_MACHINE\SYSTEM key
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
//Open CurrentControlSet
currentControlSet = system.OpenSubKey("CurrentControlSet");
//Go to the services key
services = currentControlSet.OpenSubKey("Services");
//Open the key for your service, and allow writing
service = services.OpenSubKey(this.serviceInstaller1.ServiceName, true);
//Add your service's description as a REG_SZ value named "Description"
service.SetValue("Description", "This is my service's description.");
//(Optional) Add some custom information your service will use...
config = service.CreateSubKey("Parameters");
}
catch(Exception e)
{
Console.WriteLine("An exception was thrown during service installation:\n" + e.ToString());
}
}
public override void Uninstall(IDictionary stateServer)
{
Microsoft.Win32.RegistryKey system,
currentControlSet,
services,
service;
try
{
//Drill down to the service key and open it with write permission
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
currentControlSet = system.OpenSubKey("CurrentControlSet");
services = currentControlSet.OpenSubKey("Services");
service = services.OpenSubKey(this.serviceInstaller1.ServiceName, true);
//Delete any keys you created during installation (or that your service created)
service.DeleteSubKeyTree("Parameters");
//...
}
catch(Exception e)
{
Console.WriteLine("Exception encountered while uninstalling service:\n" + e.ToString());
}
finally
{
//Let the project installer do its job
base.Uninstall(stateServer);
}
}
将上述代码添加到您的 ProjectInstaller 类后,在您的服务安装完成后,您应该会在服务名称旁边看到服务的描述。 在未来的文章中,我们将探讨如何将描述添加为自定义属性,并扩展 ServiceInstaller 类以自动为我们添加描述。