UAC或Userlevel如何克服它!

Adr*_*ian 1 c# permissions service uac elevation

我正在尝试以编程方式从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
  {
    // ...
  }
}
Run Code Online (Sandbox Code Playgroud)

m0s*_*0sa 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
  { 
   // ...
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

在您的项目中,添加对上层项目的引用,并使用类似的东西来调用可执行文件.不使用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...
Run Code Online (Sandbox Code Playgroud)