2011-08-23 62 views
0

我想從我的wpf應用程序啓動一項服務,我正在嘗試在計算機上無法打開SERVICENAME服務啓動/停止服務....從我的WPF開始一個窗口服務c#給「無法在計算機上打開SERVICENAME服務」。「

我必須這樣做編程我不能改變任何設置或手動權限...

ServiceController service = ServiceController.GetServices().FirstOrDefault(i => i.ServiceName.Contains("SERVICENAME")); 

      if (service.Status != ServiceControllerStatus.Running) 
      { 
       service.Start();// /// Cannot open SERVICENAME service on computer '.'. 
       service.WaitForStatus(ServiceControllerStatus.Running); 
      } 
+0

權限問題?您的WPF應用程序需要以具有足夠權限的用戶身份運行或模擬具有啓動/停止服務的用戶。 –

回答

1

我猜你沒有足夠的權限由於UAC的控制服務。嘗試以管理員身份運行,即提升您的特權。

+0

以管理員身份運行將解決該問題...但要求用戶以管理員模式啓動應用程序是不合理的。有些可能沒有足夠的特權,我知道沒有其他方法可以執行此操作,而不是拋出錯誤消息。 – Bathineni

+0

默認情況下,服務只能由擁有管理員權限的用戶啓動或停止。您可以在安裝時添加ACL,以允許標準用戶執行此操作。有問題的服務是由您撰寫的嗎? –

+0

否..服務不是由我寫的..它是第三方組件 – Bathineni

2

這可能不是一個問題,如果你是一個XP的計算機上或視覺工作室的調試器下運行,但只有當你在Windows 7機器上部署你的程序,你看到的錯誤:

Cannot open < servicename > service on computer '.'.

這很可能是因爲自Vista關於用戶帳戶控制後發生的權限更改。

如果您嘗試以管理員身份運行應用程序並且問題沒有發生,您可以驗證這確實是導致問題的原因。

爲了啓動或停止Windows服務,您需要運行具有管理權限的C#程序。

這既可以手動完成,通過右擊應用程序,然後單擊「以管理員身份運行」

或者,這可以通過編程設置你的程序總是與管理權限運行,如果您添加完成下面在位於屬性文件夾在解決方案資源管理項目的app.manifest文件代碼:

<assemblyIdentity version="1.0.0.0" name="MyApplication.app" /> 
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> 
<security> 
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> 
<!-- UAC Manifest Options 
    If you want to change the Windows User Account Control level replace the 
    requestedExecutionLevel node with one of the following. 

<requestedExecutionLevel level="asInvoker" uiAccess="false" /> 
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> 
<requestedExecutionLevel level="highestAvailable" uiAccess="false" /> 

    If you want to utilize File and Registry Virtualization for backward 
    compatibility then delete the requestedExecutionLevel node. 
--> 
<requestedExecutionLevel level="asInvoker" uiAccess="false" /> 
</requestedPrivileges> 
<applicationRequestMinimum> 
<defaultAssemblyRequest permissionSetReference="Custom" /> 
<PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true" ID="Custom" SameSite="site" /> 
</applicationRequestMinimum> 
</security> 
</trustInfo> 
</asmv1:assembly> 

你可以找到關於創建和嵌入應用程序清單(UAC)更多信息在這裏: https://msdn.microsoft.com/en-us/library/bb756929.aspx