這可能不是一個問題,如果你是一個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
權限問題?您的WPF應用程序需要以具有足夠權限的用戶身份運行或模擬具有啓動/停止服務的用戶。 –