SoFunction
Updated on 2025-03-07

Change the service startup type by calling cmd through C#


using System;
using ;
using ;
using ;
using ;
using ;
using Microsoft.Win32;
namespace Service
{
public class ClassService
{
private string ServiceName; //Service name
private ServiceController sc;
/// <summary>
/// Service operation
/// </summary>
/// <param name="ServiceName">Service Name</param>
public ClassService(string ServiceName)
{
= ServiceName;
= new ServiceController(ServiceName);
}
/// <summary>
/// Start the service
/// </summary>
/// <returns></returns>
public bool StartService()
{
try
{
if ( != )
();
else
return false;
}
catch (Exception)
{
return false;
}
return true;
}
/// <summary>
/// Stop service
/// </summary>
/// <returns></returns>
public bool StopService()
{
try
{
if ( != )
();
else
return false;
}
catch (Exception)
{
return false;
}
return true;
}
/// <summary>
/// Restart the service
/// </summary>
/// <returns></returns>
public bool RestartService()
{
if (StopService())
{
if (StartService())
return true;
else
return false;
}
else
return false;
}
/// <summary>
/// Get the service startup type
/// </summary>
/// <returns>2:Automatic 3:Manual 4:Disable 0:Failed</returns>
public int GetServiceStartMode()
{
int Mode = 0;
try
{
RegistryKey key = (@"SYSTEM\CurrentControlSet\services\" + ServiceName);
Mode = Convert.ToInt32(("Start"));
();
}
catch (Exception)
{
return 0;
}
return Mode;
}
/// <summary>
/// Set the service startup type
/// </summary>
/// <param name="Mode">2:Automatic 3:Manual 4:Disable</param>
/// <returns></returns>
public bool SetServiceStartMode(int Mode)
{
try
{
RegistryKey key = (@"SYSTEM\CurrentControlSet\services\" + ServiceName, true);
("Start", Mode);
();
}
catch (Exception)
{
return false;
}
return true;
}
}
}