1

I want to install a service to Service Manager and run it. My code is as follows:

 using System;
 using System.Runtime.InteropServices;
 class Ana
 {
    static void Main()
    {
        IntPtr sc_handle=OpenSCManager(null,null,2);
        IntPtr sv_handle = CreateService(sc_handle, "deneme", "deneme", 16, 16, 2, 0, @"D:\ServisDeneme2.exe", null, null, null, null, null);
        int i=StartService(sv_handle,0,null);
        CloseServiceHandle(sc_handle);
    }

    [DllImport("advapi32.dll")]
    public static extern IntPtr OpenSCManager(string machine, string db, int parameter);

    [DllImport("advapi32.dll")]
    public static extern IntPtr CreateService(IntPtr SC_HANDLE, string lpSvcName, string lpDisplayName, int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpPathName, string lpLoadOrderGroup, object lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword);

    [DllImport("advapi32.dll")]
    public static extern void CloseServiceHandle(IntPtr SCHANDLE);

    [DllImport("advapi32.dll")]
    public static extern int StartService(IntPtr SVHANDLE, int dwNumServiceArgs, string[] lpServiceArgVectors); 
}

This code works perfectly on my 32 bit computer but does not work on 64 bit computer. How can I do the same work for 64 bit?

  • 1
    The declarations are buggy. Right now you surely fall over on CreateService's lpdwTagId argument, it is actually `out int`. You probably don't want to use it at all, declare it *object* and pass null. StartService is wrong too, not fatal, last argument is string[]. – Hans Passant Mar 28 '16 at 22:23
  • I have edited the code. Now it works on my 32 bit computer. But how can I make it work on 64 bit? – user1067742 Mar 29 '16 at 12:10

2 Answers2

0

I would assume you would have to compile the app in x86 for it to function properly on a 64 bit machine.

Or you can do something like this guy did:

Using a 32bit or 64bit dll in C# DllImport

Community
  • 1
  • 1
Cole W
  • 15,123
  • 6
  • 51
  • 85
0

I have done it! The problem was not having administrator rights. It is not related to 32 bit/64 bit distinction. To create, start, stop a service the service control program must have administrator rights. I've started the command line with administrator rights and the program worked.