Question

I'm trying to programmatically restart a service from within a helper application written in C# (on .net 4.0) but I get a permission violation if I run the EXE by double clicking while right clicking and doing "run as Administrator" works.

But why do I need this the users are local admins?!

I would like the app to run normally and only request admin rights when the user click the button to restart the service. Can this be done?

The solution needs to work on xp, vista and windows 7.

I'm using this code from 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
  {
    // ...
  }
}
Was it helpful?

Solution

Make a new console app project like this:

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
  { 
   // ...
  }
 }
}

In your project, add a reference to the upper project and use something like this to call the executable. Not the use of the runas verb, which will prompt the user for elevation rights.

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

OTHER TIPS

You can't skip/ignore the UAC permission request (that would essentially negate it's whole use) but PrincipalPermissionAttribute might be what you're looking for. Never used it so far though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top