怎么利用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修改是没有效果的。
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源