WindowsアプリケーションからWindowsサービスを開始しようとするSystem.comPonentModel.win32Exception:アクセスが拒否されます

StackOverflow https://stackoverflow.com/questions/4407796

質問

2つの特定のサービスのステータスを起動/停止および監視するためのWindowsアプリケーションを開発しようとしています。

問題は私が得ていることです

System.comPonentModel.win32Exception:アクセスは拒否されます

両方のサービスはローカルシステムであることに注意してください

以下は私のコードです

private void StartService(string WinServiceName)
{
  ServiceController sc = new ServiceController(WinServiceName,".");
try
{
  if (sc.ServiceName.Equals(WinServiceName))
  {
  //check if service stopped
    if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Stopped))
    {
       sc.Start();
    }
    else if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Paused))
    {
        sc.Start();
    }
  }

}
catch (Exception ex)
{
  label3.Text = ex.ToString();
  MessageBox.Show("Could not start " + WinServiceName + "Service.\n Error : " + ex.ToString(), "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
   sc.Close();
   sc.Dispose();
   // CheckStatus();
}
}
役に立ちましたか?

解決

レッピーが彼のコメントで提案したことを試してみてください。それがうまくいかない場合は、どのラインが例外をスローしているかを教えてくれる必要があります - ServiceControllerを作成しているとき、それを開始しようとしているとき、またはどこかから

ところで、サービスが一時停止した場合は、SC.Start()に電話してはなりません。SC.Continue()に電話する必要があります。

また、おそらく使用する方が良いでしょう 使用 このように、試してみる/最後に構成します:

private void StartService(string WinServiceName)
{
    try
    {
        using(ServiceController sc = new ServiceController(WinServiceName,"."))
        {
            if (sc.ServiceName.Equals(WinServiceName))
            {
                //check if service stopped
                if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Stopped))
                {
                   sc.Start();
                }
                else if (sc.Status.Equals(System.ServiceProcess.ServiceControllerStatus.Paused))
                {
                    sc.Continue();
                }
            }
        }
    }
    catch (Exception ex)
    {
        label3.Text = ex.ToString();
        MessageBox.Show("Could not start " + WinServiceName + "Service.\n Error : " + ex.ToString(), "Error Occured", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

そうすれば、sc.close()自分で電話をかける必要はありません(ところで、閉じるだけで済むだけで済みます - 冗長なドキュメント:このServiceControllerインスタンスをサービスから切断し、インスタンスが割り当てたすべてのリソースを解放します。)

編集: alt text

ExplorerのExeファイルを右クリックし、管理者として実行を選択します。 Windows 7では、UAC(ユーザーアクセス制御)がオフになっていない限り、明示的に要求されるまで管理者としてプログラムを実行していません/またはそうするように求められます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top