Frage

Ich versuche programmatisch einen Service aus einer Hilfsanwendung in C # geschrieben neu starten (auf .net 4.0), aber ich eine Erlaubnis Verletzung, wenn ich die EXE-Datei durch einen Doppelklick ausführen, während der rechte Maustaste und „Als Administrator ausführen“ zu tun funktioniert.

Aber warum muss ich diese die Benutzer lokale Administratoren?!

würde ich die App gefällt, normal zu laufen und verlangen nur Admin-Rechte, wenn der Benutzer auf die Schaltfläche klicken Sie den Dienst neu zu starten. Kann dies geschehen?

Die Lösung geht, die Arbeit an XP, Vista und Windows 7.

Ich verwende diesen Code von http: //www.csharp-examples. net / Neustart-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
  {
    // ...
  }
}
War es hilfreich?

Lösung

Machen Sie

eine neue Konsolenanwendung Projekt wie folgt:

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 einem Projekt, fügen Sie einen Verweis auf das obere Projekt und die Verwendung so etwas wie dies die ausführbare Datei zu nennen. Nicht die Verwendung des runas Verb, das den Benutzer zur Erhebung Rechte fordert.

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

Andere Tipps

Sie können nicht überspringen / ignorieren die UAC Berechtigungsanfrage (das wäre es ganzer Gebrauch im Wesentlichen negieren), aber

scroll top