2

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();
}
}
4

1 に答える 1

3

leppie が彼のコメントで提案したことを試してみてください。うまくいかない場合は、例外をスローしている行を教えてください - ServiceController を作成しているとき、それを開始しようとしているとき、または他の場所で。

ところで、サービスが一時停止している場合は、sc.Start() を呼び出すべきではありません。sc.Continue() を呼び出す必要があります。

また、次のように、try/finally よりもusing構造を使用する方がおそらく良い考えです。

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() を自分で呼び出す必要はありません (ところで、Close だけを呼び出す必要があるのは Dispose だけです。冗長です。Close のドキュメント: サービスからこの ServiceController インスタンスを切断し、インスタンスが割り当てたすべてのリソースを解放します。)

編集代替テキスト

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

于 2010-12-10T11:33:32.620 に答える