Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi i am trying to execute a c# program which should restart a service when a lan cable is unplugged and plugged back to system. Please help me.

What I have tried:

I have tried restarting the service for a certain time period, but i need it when a lan is unplugged and plugged in back.

C#
public static void RestartService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    int millisec1 = Environment.TickCount;
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);

    service.Stop();
    service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);

    // count the rest of the timeout
    int millisec2 = Environment.TickCount;
    timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));

    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
Posted
Updated 11-Jan-17 17:47pm

1 solution

You could monitor NetworkChange.NetworkAvailabilityChanged Event (System.Net.NetworkInformation)[^] in order to react upon changes.

However, I must say that it sounds odd that a separate program restarts the service this way. In most situations I believe that the service should autonomously handle the situation.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900