C#启动Windows编程服务 [英] C# start Windows Service programmatically

查看:175
本文介绍了C#启动Windows编程服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我创建一个应用程序的问题。我想通过我的C#应用​​程序启动Windows服务。当我点击我的启动按钮,看起来一切顺利通过,但是当我登录到服务器,该服务仍无法显示它正在运行。不过,我运行它的第二次,我得到的说服务的实例已经运行异常。当我再次登录到服务器,该服务似乎停止。有没有人见过这个?

I am having an issue with an application that I am creating. I am trying to start a windows service through my C# app. When I click my start button, it looks like everything goes through but when I log into the server, the service still does not show that it is running. However, the second time I run it, I get an exception that says the instance of the service is already running. Again when I log into the server, the service appears to be stopped. Has anyone ever seen this?

下面是我的代码。

try
{
    while (reader.Read())
    {
        int timeoutMilliseconds = 1000;
        string serviceName = reader["ServiceName"].ToString();
        string permission = reader["Permission"].ToString();

        if (permission == "E")
        {
            lblServStartSuccess.Visible = true;

            ServiceController service = new ServiceController(serviceName);
            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        }
        else
        {
            lblServErrorStart.Visible = true;
        }
    }
}
catch (Exception ex)
{
    Response.Write(ex.ToString());
}



编辑:这是我的一个服务接收到异常:

Here is the exception I received on one service:

System.InvalidOperationException:服务逻辑磁盘管理器管理服务没有计算机发现。。 ---> System.ComponentModel.Win32Exception:指定的服务不存在作为安装服务---内部异常堆栈跟踪的结尾---

System.InvalidOperationException: Service Logical Disk Manager Administrative Service was not found on computer '.'. ---> System.ComponentModel.Win32Exception: The specified service does not exist as an installed service --- End of inner exception stack trace ---

我知道服务存在。我是否需要在服务的前面添加的东西告诉它看什么服务器?

I know the service exists. Do I need to add something in front of the service to tell it what server to look at?

推荐答案

如果你表现出码在不同的机器比这里的服务是应该运行在执行时(我不是您的意见清楚,如果是这样的话与否),你就需要在ServiceController的建筑工提供机器名。是否有可能在成功启动该服务,但你不觉得在机器上? 。这将适合你描述的症状

If the code you showed is executing on a different machine than where the service is supposed to run (I'm not clear from your comments if that's the case or not), you would need to provide the machine name in the ServiceController constructer. Is it possible you are successfully starting the service, but not on the machine you think? That would fit the symptoms you describe.

  ServiceController service = new ServiceController(serviceName, serverName);

http://msdn.microsoft.com/en-us/library/aa331793%28v=VS.71%29.aspx

这篇关于C#启动Windows编程服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆