手机
当前位置:查字典教程网 >编程开发 >C#教程 >怎么利用c#修改services的Startup type
怎么利用c#修改services的Startup type
摘要:我们知道大部分的services的操作可以通过ServiceController来实现,包括services的开启,停止,暂停,还有获取se...

我们知道大部分的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("rootCIMV2",

"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修改是没有效果的。

【怎么利用c#修改services的Startup type】相关文章:

C# 获取属性名的方法

C#中一些字符串操作的常用用法

用C#操纵IIS(代码)

浅谈关于C#的垃圾回收机制

用 C# Winform做出全透明的磨砂玻璃窗体效果代码

c# 以二进制读取文本文件

C#实现对AES加密和解密的方法

重写、隐藏基类(new, override)的方法

C#难点逐个击破(5):类的访问类型

winform中写app.config文件时调试情况下没有改变的原因

精品推荐
分类导航