用户登录
用户注册

分享至

怎么利用c#修改services的Startup type

  • 作者: ADAMSIR
  • 来源: 51数据库
  • 2021-11-01

我们知道大部分的services的操作可以通过servicecontroller来实现,包括services的开启,停止,暂停,还有获取service的status。但是这里关于services的修改startup type这点,貌似servicecontroller不好做到,我们可以这样来做:

复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.management;

namespace servicesstartup
{
    class program
    {
        public enum startuptype
        {
            automatic,
            disabled,
            manual
        }

        public static void setstartuptype(string servicename, startuptype startuptype)
        {
            string type = startuptype.tostring();
            try
            {
                managementpath mp = new managementpath(string.format("win32_service.name='{0}'", servicename));
                if (mp != null)
                {
                    using (managementobject mo = new managementobject(mp))
                    {
                        object[] parameters = new object[1] { type };
                        mo.invokemethod("changestartmode", parameters);                       
                    }
                }
            }
            catch (managementexception ex)
            {
                console.writeline("an error occured while trying to searching the wmi method: " + ex.tostring());
            }

        }

        static void main(string[] args)
        {
            setstartuptype("gupdate", startuptype.automatic); 
            console.readkey();
        }
    }
}


上面使用了managementpath类,或者你也可以这样:
复制代码 代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.management;

namespace servicesstartup
{
    class program
    {
       static void main(string[] args)
        {
            try
            {
                managementobject classinstance = new managementobject("root\\cimv2",
                    "win32_service.name='gupdate'", null);

                // obtain in-parameters for the method.
                managementbaseobject inparams = classinstance.getmethodparameters("changestartmode");
                // add the input parameters.
                inparams["startmode"] = "automatic";               

                // execute the method and obtain the return values.
                managementbaseobject outparams = classinstance.invokemethod("changestartmode", inparams, null);

                // list outparams
                console.writeline("out parameters:");
                console.writeline("returnvalue: " + outparams["returnvalue"]);
            }
            catch (managementexception err)
            {
                console.writeline("an error occured while trying to execute the wmi emthod: " + err.tostring());
            }
            console.readkey();
        }
    }
}


这段代码使用的是managementobject类,里面输出的returnvalue是一个标志,如果值为0就是修改成功了。

这里需要注意的一点:c#必须以管理员的权限运行才能达到效果的,不然service的startmode修改是没有效果的。

软件
前端设计
程序设计
Java相关