How to install a service programmatically in C#

0

I am having a Form : InstallerForm.cs

public partial class InstallerForm : Form
{
  private void InstallerForm_Load(object sender, EventArgs e)
  {
   //Check if service is installed
   ServiceInstaller.ServiceIsInstalled("MyServiceName");
  }
}

public class ServiceInstaller
{
 private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
 private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;

 [StructLayout(LayoutKind.Sequential)]
 private class SERVICE_STATUS
 {
  public int dwServiceType = 0;
  public ServiceState dwCurrentState = 0;
  public int dwControlsAccepted = 0;
  public int dwWin32ExitCode = 0;
  public int dwServiceSpecificExitCode = 0;
  public int dwCheckPoint = 0;
  public int dwWaitHint = 0;
 }

 [DllImport("advapi32.dll", EntryPoint = "OpenSCManagerA")]
 private static extern IntPtr OpenSCManager(ServiceManagerRights dwDesiredAccess);
  
 public static bool ServiceIsInstalled(string ServiceName)
 {
     IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);
      try
      {
         IntPtr service = OpenService(scman, ServiceName,
         ServiceRights.QueryStatus);
         if (service == IntPtr.Zero) return false;
         CloseServiceHandle(service);
          return true;
       }
       finally
       {
          CloseServiceHandle(scman);
        }
   }
}
  [Flags]
  public enum ServiceManagerRights
    {
        Connect = 0x0001,
        CreateService = 0x0002,
        EnumerateService = 0x0004,
        Lock = 0x0008,
        QueryLockStatus = 0x0010,
        ModifyBootConfig = 0x0020,
        StandardRightsRequired = 0xF0000,
        AllAccess = (StandardRightsRequired | Connect | CreateService |
        EnumerateService | Lock | QueryLockStatus | ModifyBootConfig)
    }

This is my initial code to check MyService is installed or not. But on this point

IntPtr scman = OpenSCManager(ServiceManagerRights.Connect);

I am getting an Exception like "System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.' "

Is it because of the [DllImport("advapi32.dll")] can i get any assistance on this??

c#
asp.net
.net
asked on Stack Overflow Dec 10, 2020 by fia • edited Dec 10, 2020 by fia

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0