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 に答える