1

我正在尝试从用 C#(在 .net 4.0 上)编写的帮助应用程序中以编程方式重新启动服务,但是如果我在右键单击并执行“以管理员身份运行”时双击运行 EXE 会出现权限冲突。

但是为什么我需要这个用户是本地管理员?!

我希望该应用程序能够正常运行,并且仅在用户单击按钮以重新启动服务时才请求管理员权限。这可以做到吗?

该解决方案需要在 xp、vista 和 windows 7 上运行。

我正在使用来自http://www.csharp-examples.net/restart-windows-service/的代码

public static void RestartService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    int millisec1 = Environment.TickCount;
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Stop();
    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

    // count the rest of the timeout
    int millisec2 = Environment.TickCount;
    timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));

    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
  catch
  {
    // ...
  }
}
4

2 回答 2

5

像这样创建一个新的控制台应用程序项目:

public class RunService
{
 static int Main()(string[] args)
 {
  //TODO read serviceName and timeoutMilliseconds from args
  ServiceController service = new ServiceController(serviceName);
  try
  {
    int millisec1 = Environment.TickCount;
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Stop();
    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

    // count the rest of the timeout
    int millisec2 = Environment.TickCount;
    timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));   service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
    // TODO return status code
  }
  catch
  { 
   // ...
  }
 }
}

在您的项目中,添加对上层项目的引用并使用类似这样的东西来调用可执行文件。不使用 runas 动词,它会提示用户提升权限。

var process = Process.Start(new ProcessStartInfo
                        {
                            Verb = "runas",
                            FileName = typeof(RunService).Assembly.Location,
                            UseShellExecute = true,
                            CreateNoWindow = true,
                        });
process.WaitForExit();
var exitCode = process.ExitCode
// TODO process exit code...
于 2010-11-25T23:58:23.543 回答
2

您不能跳过/忽略 UAC 权限请求(这基本上会否定它的全部使用)但PrincipalPermissionAttribute可能是您正在寻找的。到目前为止从未使用过它。

于 2010-11-26T00:04:28.217 回答