简体   繁体   English

无法在计算机“。”上打开Servicename服务。 使用C#以编程方式启动Windows Service时出错

[英]Cannot open Servicename service on computer '.'. Error on Starting Windows Service programatically using c#

I have made a Windows Service and installed it on my system.Now as per my requirement i have to start and stop this windows Service using Button click from Windows Form Application. 我已经制作了Windows服务并将其安装在系统上。现在,根据我的要求,我必须使用Windows窗体应用程序中的“按钮单击”来启动和停止此Windows服务。 Here is my Code .. 这是我的代码..

public partial class Form1 : Form
{
    string svcStatus;
    ServiceController myService;

    public Form1()
    {
        InitializeComponent();

        myService = new ServiceController();
        myService.ServiceName = "ServiceName";
        svcStatus = myService.Status.ToString();
    }


    private void button1_Click(object sender, EventArgs e)
    {
        if (svcStatus == "Stopped")
        {
            myService.Start();   // START the service if it is already Stopped

            string svcStatusWas = "";  
            while (svcStatus != "Running")
            {
                if (svcStatus != svcStatusWas)
                {
                    Console.WriteLine("Status: " + svcStatus);
                }

                svcStatusWas = svcStatus;

                myService.Refresh();
                svcStatus = myService.Status.ToString();
            }
            Console.WriteLine("Service Started!!");
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (svcStatus == "Running")
        {                
            myService.Stop();   // STOP the service if it is already Running

            string svcStatusWas = "";   
            while (svcStatus != "Stopped")
            {

                svcStatusWas = svcStatus;

                myService.Refresh();    
                svcStatus = myService.Status.ToString();
            }
            Console.WriteLine("Service Stopped!!");
        }
    }     
}

} }

I am getting error "Cannot open Servicename service on computer '.'." 我收到错误消息“无法在计算机'。'上打开Servicename服务”。 at this line myService.Start(); 在此行myService.Start();

Please help me. 请帮我。

This is probably not an issue if you are running on an XP machine or under the debugger of Visual Studios, but only when you deploy your program on a Windows 7 machine you see the error: 如果您是在XP机器上或在Visual Studios的调试器下运行,则可能不是问题,但是只有在Windows 7机器上部署程序时,您才会看到错误:

Cannot open < servicename > service on computer '.'. 无法在计算机“。”上打开<servicename>服务。

This is most likely because of the privileges change which occurred since Vista regarding the User Account Control. 这很可能是因为自Vista以来,有关用户帐户控制的权限发生了更改。

You can validate that this is indeed what is causing the issue if you try running the application as administrator and the issue does not occur. 如果您尝试以管理员身份运行该应用程序并且没有发生此问题,则可以验证这确实是导致该问题的原因。

In order to Start or Stop a Windows services you need to run your C# program with administration rights. 为了启动或停止Windows服务,您需要以管理权限运行C#程序。

This can either be done manually, by right clicking on the application and then click 'Run as administrator' 可以通过右键单击应用程序,然后单击“以管理员身份运行”来手动完成此操作

Or this can be done programmatically by setting your program to always run with administration right if you add the below code in your app.manifest file located in the Properties folder in your project in Solution Explorer: 或者,如果您将以下代码添加到位于解决方案资源管理器中项目的“属性”文件夹中的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>

You can find more info on Creating and Embedding an Application Manifest (UAC) here: https://msdn.microsoft.com/en-us/library/bb756929.aspx 您可以在这里找到有关创建和嵌入应用程序清单(UAC)的更多信息: https : //msdn.microsoft.com/zh-cn/library/bb756929.aspx

Pranav, you need to run your application with Administrator privileges. Pranav,您需要使用管理员权限运行您的应用程序。 If you run Visual Studio as an administrator, your application should work correctly in debug mode. 如果您以管理员身份运行Visual Studio,则您的应用程序应在调试模式下正常运行。

When you come to deploy your application, you can either run it in administrator mode by default, or assign the appropriate privileges to your application to enable it to start and stop particular services (I believe this is done on the command line). 部署应用程序时,可以默认在管理员模式下运行它,也可以为应用程序分配适当的特权,以使其能够启动和停止特定服务(我相信这是在命令行上完成的)。 I have done this a while ago, and a quick Google search will help you. 我已经做过一段时间了,快速的Google搜索将为您提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM