如果Windows服务被禁用(不使用注册表)查询? [英] Querying if a Windows Service is disabled (without using the Registry)?
问题描述
有没有一个.NET(C#)方法或API调用,我可以用它来查询,如果一个Windows服务被禁用?有关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 = @"System\CurrentControlSet\services\";
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屋!