我正在尝试从C#(ON .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
  {
    // ...
  }
}
有帮助吗?

解决方案

制作一个新的控制台应用程序项目:

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...

其他提示

您不能跳过/忽略UAC权限请求(从本质上否定了它的整体用途),但是 princionalPermissionAttribute 可能是您想要的。到目前为止,从未使用过。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top