Preface:
Recently, I am working on problems related to application installation.
Window Time Service is used in the system to synchronize time.
However, when starting this service.
However, we found that using managementobject class to control WMI,
Windows Service Startup type cannot be set to automatic (delay starts )」.
After Google search,
You can use the Windows SC command to manage Windows Services.
In this way, you can set the Windows Service Startup type to "automatic (delay starts )」.
A simple record of this article,
How does a. NET application use the Windows SC command to set the Windows Service Startup type.
Method:
The overall approach is as follows:
1. Execute an invisible cmd.exe.
2. cmd.exe calls the Windows SC command to control the Windows Service Startup type.
3. The invisible cmd.exe cannot get the execution message and cannot judge the execution error.
Restrict input, data verification, and troubleshooting to minimize the chance of execution errors.
The following program encapsulates the above action as a function,
Before using the service, you must add system. serviceprocess reference and call to set the Windows Service Startup type.
Example:
SetWindowsServiceStartupType("w32time", StartupType.AutomaticDelayed);
Original code:
public enum StartupType{ Automatic, Manual, Disabled, AutomaticDelayed, } public static void SetWindowsServiceStartupType(String serviceName, StartupType startupType, int timeoutMilliseconds = 0){ // ServiceName if (string.IsNullOrEmpty(serviceName) == true) { throw new ArgumentException("serviceName"); } // StartType string startupTypeString = string.Empty; switch (startupType) { case StartupType.Automatic: startupTypeString = "auto"; break; case StartupType.Manual: startupTypeString = "demand"; break; case StartupType.Disabled: startupTypeString = "disabled"; break; case StartupType.AutomaticDelayed: startupTypeString = "delayed-auto"; break; default: throw new ArgumentException("startupType"); } // TimeoutMilliseconds if (timeoutMilliseconds < 0) { throw new ArgumentException("timeoutMilliseconds"); } // Check Existed bool isExisted = false; foreach (ServiceController serviceController in ServiceController.GetServices()) { if (string.Compare(serviceController.ServiceName, serviceName, true) == 0) { isExisted = true; break; } } if (isExisted == false) throw new Exception("Service not existed."); // Execute String result = string.Empty; using (System.Diagnostics.Process process = new System.Diagnostics.Process()) { process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = string.Format("/c sc config {0} start= {1}", serviceName, startupTypeString); process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; process.StartInfo.CreateNoWindow = false; process.Start(); if (timeoutMilliseconds == 0) { process.WaitForExit(); } else { if (process.WaitForExit(timeoutMilliseconds) == false) { process.Kill(); throw new System.TimeoutException(); } } }}