Last active
August 29, 2024 07:59
-
-
Save tommyready/552f2d177239d9acfda63d786596c29f to your computer and use it in GitHub Desktop.
Using C# to Restart a Windows Service.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ServiceProcess; | |
using System.Diagnostics; | |
namespace RestartService | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
try | |
{ | |
string serviceToRestart = args[0]; // Set Service Name | |
Console.WriteLine("Begining Restart of " + serviceToRestart); | |
RestartService(serviceToRestart, 60000); // Restart Service w/60 Seconds for Timeout | |
} catch (Exception e) | |
{ | |
// Log Error Message | |
using (EventLog eventLog = new EventLog("Application")) | |
{ | |
eventLog.Source = "RestartServiceConsole"; | |
eventLog.WriteEntry(e.Message, EventLogEntryType.Error, 101, 1); | |
} | |
Console.WriteLine(e.Message); | |
Console.ReadLine(); | |
} | |
} | |
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(); | |
Console.WriteLine("Stopping " + serviceName + "............."); | |
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); | |
// count the rest of the timeout | |
int millisec2 = Environment.TickCount; | |
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1)); | |
service.Start(); | |
Console.WriteLine("Starting " + serviceName + "............."); | |
service.WaitForStatus(ServiceControllerStatus.Running, timeout); | |
} catch( Exception e ) | |
{ | |
// Log Error Message | |
using (EventLog eventLog = new EventLog("Application")) | |
{ | |
eventLog.Source = "RestartServiceConsole"; | |
eventLog.WriteEntry(e.Message, EventLogEntryType.Error, 101, 1); | |
} | |
Console.WriteLine("Error Restarting " + serviceName); | |
Console.WriteLine(e.Message); | |
Console.ReadLine(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment