Window Service Startup Mode
-
hi all, i created a windows service and build a controller to that service, just as the SQL Server Service Manager if any saw it. Anyway the problem is i want to control the startup mode of the windows service (Automatic, Manual, Disabled), in .Net you can specify this in the Service Installer but after that i didn't find a way to change it. Does anyone know a way to change the startup mode of the Windows Service in .Net? i think that i foud a way to do it in win32, but i need it in .Net... thanks for help
-
hi all, i created a windows service and build a controller to that service, just as the SQL Server Service Manager if any saw it. Anyway the problem is i want to control the startup mode of the windows service (Automatic, Manual, Disabled), in .Net you can specify this in the Service Installer but after that i didn't find a way to change it. Does anyone know a way to change the startup mode of the Windows Service in .Net? i think that i foud a way to do it in win32, but i need it in .Net... thanks for help
The Service startup mode can be changed in C# using System.Management namespace. a sample method is given below.
/// <summary>
/// This routine updates the start mode of the provided service.
/// Add Reference to System.Management .net Assembly
/// </summary>
/// <param name="serviceName">Name of the service to be updated</param>
/// <param name="startMode">Manual or Automatic. This parameter could probably use
/// an enum.</param>
/// <param name="errorMsg">If applicable, error message assoicated with exception</param>
/// <returns>Success or failure. False is returned if service is not found.</returns>
public bool ServiceStartModeUpdate(string serviceName, string startMode, out string errorMsg)
{
uint success = 1;
errorMsg = string.Empty;string filter = String.Format("SELECT \* FROM Win32\_Service WHERE Name = '{0}'", serviceName); System.Management.ManagementObjectSearcher query = new ManagementObjectSearcher(filter); // No match = failed condition if (query == null) return false; try { ManagementObjectCollection services = query.Get(); foreach (ManagementObject service in services) { ManagementBaseObject inParams = service.GetMethodParameters("ChangeStartMode"); inParams\["startmode"\] = startMode; ManagementBaseObject outParams = service.InvokeMethod("ChangeStartMode", inParams, null); success = Convert.ToUInt16(outParams.Properties\["ReturnValue"\].Value); //custom method errorMsg = GetErrorMsg(success) + "\\n Try \\"Run as Administrator\\" "; } } catch (Exception ex) { errorMsg = ex.Message; throw; } return (success == 0); }