Click here to Skip to main content
13,085,613 members (60,477 online)
Rate this:
Please Sign up or sign in to vote.
See more:
I am having a Windows Forms application, from which I want to restart services for various different servers. According to the value entered in textbox on button click event, the application should connect to that server and service should start. For this I have written the following code and it is showing that it is working but actually it is not working without any error. If any budy having any type of solution please let me know.
class Program
    static void Main(string[] args)
        Impersonate.ImpersonateNow("ip", "machineName", "password");
        string serviceName = "AxInstSV";
          int timeoutMilliseconds = 1000;
        ServiceController service = new ServiceController(serviceName);
            int millisec1 = Environment.TickCount;
            TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
            if (service.Status == ServiceControllerStatus.Running || service.Status == ServiceControllerStatus.Paused)
                service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            // count the rest of the timeout
            int millisec2 = Environment.TickCount;
            timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1));
            if (service.Status == ServiceControllerStatus.Stopped || service.Status == ServiceControllerStatus.StopPending)
                service.WaitForStatus(ServiceControllerStatus.Running, timeout);
        Console.WriteLine("Service has been restarted");
Posted 20-Dec-12 20:46pm
Updated 21-Dec-12 0:16am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

Nice solution, especially usage impersonation of user at first line in Main method.
This was quite necessary for reaching and injecting all of the necessary user rights on remote PC.

But!! Have you ever seen the third overload of ServiceController ctor?)
If not , please check it on MSDN. It gives to you 1 additional parameter,machine name ,or in your case it coul be an IP address.

And the last one, Does any of remote machine located in the same domain ? If not , you approach will fail anyway.
Vimal@1 21-Dec-12 4:05am
Yaa, I have overloaded this ServiceController(servicename,machinename) method, and then also i am facing same issue that i am not able to restart service on diffrent servers,

and last one, yaa all servers are in same domain.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.170813.1 | Last Updated 21 Dec 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100