Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

Here is my code.

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

EDIT: Here is the exception I received on one service:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
124 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);

Also see ServiceController constructor documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...