0

在 C# 中以编程方式停止 Windows 服务会生成下面列出的System.InvalidOperationException

{访问被拒绝}

如果我通过 Windows 界面启动/停止,那么一切正常!我是管理员用户并在 Windows 7 下运行该服务

4

3 回答 3

1

我不确定你是如何阻止它的,但我现在在我的系统上尝试了这个,这种方法至少可以正常工作:

var p = Process.Start(new ProcessStartInfo
        {
          FileName = "net",
          Arguments = "stop NameOfService",
          CreateNoWindow = true,
          WindowStyle = ProcessWindowStyle.Hidden
        });
p.WaitForExit(); //add this line if you want to make sure that the service is stopped before your program execution continues
于 2012-09-13T10:00:46.487 回答
0

如果身份验证是问题...

您可以以编程方式控制您正在使用的用户,使用

WindowsIdentity

[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LogonUser(...)

我不知道这是否可行,但值得一试。

IntPtr token IntPtr.Zero;
LogonUser(username, password ..., ref token) //and some other parameters
var identity = WindowsIdentity(token);

using(identity.Impersonate())
{ 
    //do stuff here using another identity
    //find service and stop it
}

编辑:这可用于远程服务器上的身份验证。

于 2012-09-13T20:17:11.027 回答
0

这听起来像一个 UAC 问题 - 尝试运行应以管理员身份控制服务的应用程序(右键单击“以管理员身份运行”)。

请注意,即使管理员帐户也没有完全权限,除非您在管理员模式下明确运行应用程序 - 这是为了保护用户免受 Windows Vista 中的恶意软件的侵害而引入的,并且从那时起就一直存在。

于 2012-09-13T10:00:37.943 回答