Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

c# - Querying if a Windows Service is disabled (without using the Registry)?

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");
}

I did find a simliar question but I was hoping for a better answer since the answers are presumably outdated (3 years have passed).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...