查询是否禁用了 Windows 服务(不使用注册表)? [英] Querying if a Windows Service is disabled (without using the Registry)?
问题描述
是否有可用于查询 Windows 服务是否被禁用的 .NET (C#) 方法或 API 调用?相关的 MSDN 文章在这里.
Is there a .NET (C#) method or API call that I can use to query if a Windows Service is disabled? The relevant MSDN article is here.
我想避免直接查询注册表.下面是我现在正在使用的一些代码(并且它有效).不过,我正在寻找更优雅、侵入性更小的东西.
I want to avoid querying the registry directly. Below is some of the code that I am using right now (and it works). However I am looking for something more elegant and less invasive.
const String basepathStr = @"SystemCurrentControlSetservices";
String subKeyStr = basepathStr + servicenameStr;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subKeyStr))
{
return (int) key.GetValue("Start");
}
我确实找到了一个类似的问题希望有更好的答案,因为这些答案可能已经过时(3 年过去了).
I did find a simliar question but I was hoping for a better answer since the answers are presumably outdated (3 years have passed).
推荐答案
这是我决定使用的代码中最相关的部分...感谢大家的帮助!
This the most relevant section of the code I decided to use...thanks for the help all!
StartupState state = StartupState.Unknown;
try
{
PermissionSet fullTrust = new PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
fullTrust.Demand();
string wmiQuery = @"SELECT * FROM Win32_Service WHERE Name='" + servicenameStr + @"'";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection results = searcher.Get();
foreach (ManagementObject service in results)
{
if (service["StartMode"].ToString() == "Disabled")
state = StartupState.Disabled;
else
state = StartupState.Enabled;
}
return state;
}
catch (SecurityException se)
{
return StartupState.Refused;
}
catch (Exception e)
{
return StartupState.Error;
}
这篇关于查询是否禁用了 Windows 服务(不使用注册表)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!