Installing a Windows Service Programmatically

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Hardy Wang

    #1

    Installing a Windows Service Programmatically

    Hi all:
    I read an article from
    http://www.c-sharpcorner.com/Code/20...mmatically.asp
    about how to install a windows service programmaticall y.
    Based ont the code sample, it provides the feature to install service
    under LocalSystem account.
    What I need is to install service under some other certian account. By
    further studying the code, and MSDN
    (http://msdn.microsoft.com/library/de...-us/dllproc/ba
    se/createservice.a sp) ,
    public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
    lpSvcName,strin g lpDisplayName,
    int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
    dwErrorControl, string lpPathName,
    string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string
    lpServiceStartN ame,string lpPassword);
    is the core API to create a service. And the last two parameters should be
    name and password of account under wihcih service should run. But when I
    tried to pass values to these two parameters bu calling:
    sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
    SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
    SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
    servicePath, null, 0, null, _UserName, _Password);
    This piece of code is just a bit different from original, but sv_handle
    return is 0, which means failure.

    Anybody has idea how to install a service under some certain account?


    Thanks for any suggestion.


    --
    WWW: http://hardywang.1accesshost.com
    ICQ: 3359839
    yours Hardy


  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: Installing a Windows Service Programmaticall y

    Hardy,

    If the return value is IntPtr.Zero, then throw a new instance of the
    Win32Exception class. It will detail what the error from the call to
    GetLastError is and it will give you more information about what went wrong
    with the call.

    Hope this helps.


    --
    - Nicholas Paldino [.NET/C# MVP]
    - nicholas.paldin o@exisconsultin g.com

    "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
    news:Oo$9vktdDH A.2804@TK2MSFTN GP11.phx.gbl...[color=blue]
    > Hi all:
    > I read an article from
    >[/color]
    http://www.c-sharpcorner.com/Code/20...mmatically.asp[color=blue]
    > about how to install a windows service programmaticall y.
    > Based ont the code sample, it provides the feature to install service
    > under LocalSystem account.
    > What I need is to install service under some other certian account. By
    > further studying the code, and MSDN
    >[/color]
    (http://msdn.microsoft.com/library/de...-us/dllproc/ba[color=blue]
    > se/createservice.a sp) ,
    > public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
    > lpSvcName,strin g lpDisplayName,
    > int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
    > dwErrorControl, string lpPathName,
    > string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string
    > lpServiceStartN ame,string lpPassword);
    > is the core API to create a service. And the last two parameters should be
    > name and password of account under wihcih service should run. But when I
    > tried to pass values to these two parameters bu calling:
    > sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
    > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
    > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
    > servicePath, null, 0, null, _UserName, _Password);
    > This piece of code is just a bit different from original, but sv_handle
    > return is 0, which means failure.
    >
    > Anybody has idea how to install a service under some certain account?
    >
    >
    > Thanks for any suggestion.
    >
    >
    > --
    > WWW: http://hardywang.1accesshost.com
    > ICQ: 3359839
    > yours Hardy
    >
    >[/color]


    Comment

    • Hardy Wang

      #3
      Re: Installing a Windows Service Programmaticall y

      I adding some code like:
      sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
      SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
      SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
      servicePath, null, 0, null, _UserName, _Password);

      if (sv_handle.ToIn t32() == 0) {
      CloseServiceHan dle(sc_handle);
      int err = GetLastError();
      return false;
      }

      I tried to capture the error by reading return from GetLastError(), I got
      997, where to find the definition of error code?

      --
      WWW: http://hardywang.1accesshost.com
      ICQ: 3359839
      yours Hardy
      "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com> wrote
      in message news:eWiePotdDH A.1532@TK2MSFTN GP10.phx.gbl...[color=blue]
      > Hardy,
      >
      > If the return value is IntPtr.Zero, then throw a new instance of the
      > Win32Exception class. It will detail what the error from the call to
      > GetLastError is and it will give you more information about what went[/color]
      wrong[color=blue]
      > with the call.
      >
      > Hope this helps.
      >
      >
      > --
      > - Nicholas Paldino [.NET/C# MVP]
      > - nicholas.paldin o@exisconsultin g.com
      >
      > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
      > news:Oo$9vktdDH A.2804@TK2MSFTN GP11.phx.gbl...[color=green]
      > > Hi all:
      > > I read an article from
      > >[/color]
      >[/color]
      http://www.c-sharpcorner.com/Code/20...mmatically.asp[color=blue][color=green]
      > > about how to install a windows service programmaticall y.
      > > Based ont the code sample, it provides the feature to install[/color][/color]
      service[color=blue][color=green]
      > > under LocalSystem account.
      > > What I need is to install service under some other certian account.[/color][/color]
      By[color=blue][color=green]
      > > further studying the code, and MSDN
      > >[/color]
      >[/color]
      (http://msdn.microsoft.com/library/de...-us/dllproc/ba[color=blue][color=green]
      > > se/createservice.a sp) ,
      > > public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
      > > lpSvcName,strin g lpDisplayName,
      > > int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
      > > dwErrorControl, string lpPathName,
      > > string lpLoadOrderGrou p,int lpdwTagId,strin g[/color][/color]
      lpDependencies, string[color=blue][color=green]
      > > lpServiceStartN ame,string lpPassword);
      > > is the core API to create a service. And the last two parameters should[/color][/color]
      be[color=blue][color=green]
      > > name and password of account under wihcih service should run. But when I
      > > tried to pass values to these two parameters bu calling:
      > > sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
      > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
      > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
      > > servicePath, null, 0, null, _UserName, _Password);
      > > This piece of code is just a bit different from original, but sv_handle
      > > return is 0, which means failure.
      > >
      > > Anybody has idea how to install a service under some certain[/color][/color]
      account?[color=blue][color=green]
      > >
      > >
      > > Thanks for any suggestion.
      > >
      > >
      > > --
      > > WWW: http://hardywang.1accesshost.com
      > > ICQ: 3359839
      > > yours Hardy
      > >
      > >[/color]
      >
      >[/color]


      Comment

      • Nicholas Paldino [.NET/C# MVP]

        #4
        Re: Installing a Windows Service Programmaticall y

        Hardy,

        You should never call GetLastError yourself, as it is not guaranteed to
        be accurate. The reason for this is that the runtime makes API calls
        between your API call and it might set the error state on its own. Because
        of this, you should call the static GetLastWin32Err or method on the Marshal
        class.

        However, there is a class that does all of this, the Win32Exception
        class in the System.Componen tModel namespace. You should make your call
        like this:

        // Call CreateService.
        IntPtr sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
        SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
        SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName, _Password);

        // Throw an exception if there is no handle.
        try
        {
        if (sv_handle == IntPtr.Zero)
        // Throw an exception.
        throw new Win32Exception( );
        }
        finally
        {
        CloseServiceHan dle(sc_handle);
        }

        This should give you the description of the error. You can also look in
        WINERROR.H to find the error the code represents.


        --
        - Nicholas Paldino [.NET/C# MVP]
        - nicholas.paldin o@exisconsultin g.com

        "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
        news:%23MNLettd DHA.1460@TK2MSF TNGP10.phx.gbl. ..[color=blue]
        > I adding some code like:
        > sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
        > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
        > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
        > servicePath, null, 0, null, _UserName, _Password);
        >
        > if (sv_handle.ToIn t32() == 0) {
        > CloseServiceHan dle(sc_handle);
        > int err = GetLastError();
        > return false;
        > }
        >
        > I tried to capture the error by reading return from GetLastError(), I got
        > 997, where to find the definition of error code?
        >
        > --
        > WWW: http://hardywang.1accesshost.com
        > ICQ: 3359839
        > yours Hardy
        > "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com>[/color]
        wrote[color=blue]
        > in message news:eWiePotdDH A.1532@TK2MSFTN GP10.phx.gbl...[color=green]
        > > Hardy,
        > >
        > > If the return value is IntPtr.Zero, then throw a new instance of the
        > > Win32Exception class. It will detail what the error from the call to
        > > GetLastError is and it will give you more information about what went[/color]
        > wrong[color=green]
        > > with the call.
        > >
        > > Hope this helps.
        > >
        > >
        > > --
        > > - Nicholas Paldino [.NET/C# MVP]
        > > - nicholas.paldin o@exisconsultin g.com
        > >
        > > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
        > > news:Oo$9vktdDH A.2804@TK2MSFTN GP11.phx.gbl...[color=darkred]
        > > > Hi all:
        > > > I read an article from
        > > >[/color]
        > >[/color]
        >[/color]
        http://www.c-sharpcorner.com/Code/20...mmatically.asp[color=blue][color=green][color=darkred]
        > > > about how to install a windows service programmaticall y.
        > > > Based ont the code sample, it provides the feature to install[/color][/color]
        > service[color=green][color=darkred]
        > > > under LocalSystem account.
        > > > What I need is to install service under some other certian[/color][/color][/color]
        account.[color=blue]
        > By[color=green][color=darkred]
        > > > further studying the code, and MSDN
        > > >[/color]
        > >[/color]
        >[/color]
        (http://msdn.microsoft.com/library/de...-us/dllproc/ba[color=blue][color=green][color=darkred]
        > > > se/createservice.a sp) ,
        > > > public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
        > > > lpSvcName,strin g lpDisplayName,
        > > > int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
        > > > dwErrorControl, string lpPathName,
        > > > string lpLoadOrderGrou p,int lpdwTagId,strin g[/color][/color]
        > lpDependencies, string[color=green][color=darkred]
        > > > lpServiceStartN ame,string lpPassword);
        > > > is the core API to create a service. And the last two parameters[/color][/color][/color]
        should[color=blue]
        > be[color=green][color=darkred]
        > > > name and password of account under wihcih service should run. But when[/color][/color][/color]
        I[color=blue][color=green][color=darkred]
        > > > tried to pass values to these two parameters bu calling:
        > > > sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
        > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
        > > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
        > > > servicePath, null, 0, null, _UserName, _Password);
        > > > This piece of code is just a bit different from original, but[/color][/color][/color]
        sv_handle[color=blue][color=green][color=darkred]
        > > > return is 0, which means failure.
        > > >
        > > > Anybody has idea how to install a service under some certain[/color][/color]
        > account?[color=green][color=darkred]
        > > >
        > > >
        > > > Thanks for any suggestion.
        > > >
        > > >
        > > > --
        > > > WWW: http://hardywang.1accesshost.com
        > > > ICQ: 3359839
        > > > yours Hardy
        > > >
        > > >[/color]
        > >
        > >[/color]
        >
        >[/color]


        Comment

        • Hardy Wang

          #5
          Re: Installing a Windows Service Programmaticall y

          I tried your codes, got error message "Control ID not found".

          --
          WWW: http://hardywang.1accesshost.com
          ICQ: 3359839
          yours Hardy
          "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com> wrote
          in message news:e$jjjytdDH A.1448@TK2MSFTN GP12.phx.gbl...[color=blue]
          > Hardy,
          >
          > You should never call GetLastError yourself, as it is not guaranteed[/color]
          to[color=blue]
          > be accurate. The reason for this is that the runtime makes API calls
          > between your API call and it might set the error state on its own.[/color]
          Because[color=blue]
          > of this, you should call the static GetLastWin32Err or method on the[/color]
          Marshal[color=blue]
          > class.
          >
          > However, there is a class that does all of this, the Win32Exception
          > class in the System.Componen tModel namespace. You should make your call
          > like this:
          >
          > // Call CreateService.
          > IntPtr sv_handle = CreateService(s c_handle, serviceName,[/color]
          serviceDisplayN ame,[color=blue]
          > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
          > SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName, _Password);
          >
          > // Throw an exception if there is no handle.
          > try
          > {
          > if (sv_handle == IntPtr.Zero)
          > // Throw an exception.
          > throw new Win32Exception( );
          > }
          > finally
          > {
          > CloseServiceHan dle(sc_handle);
          > }
          >
          > This should give you the description of the error. You can also look[/color]
          in[color=blue]
          > WINERROR.H to find the error the code represents.
          >
          >
          > --
          > - Nicholas Paldino [.NET/C# MVP]
          > - nicholas.paldin o@exisconsultin g.com
          >
          > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
          > news:%23MNLettd DHA.1460@TK2MSF TNGP10.phx.gbl. ..[color=green]
          > > I adding some code like:
          > > sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
          > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
          > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
          > > servicePath, null, 0, null, _UserName, _Password);
          > >
          > > if (sv_handle.ToIn t32() == 0) {
          > > CloseServiceHan dle(sc_handle);
          > > int err = GetLastError();
          > > return false;
          > > }
          > >
          > > I tried to capture the error by reading return from GetLastError(), I[/color][/color]
          got[color=blue][color=green]
          > > 997, where to find the definition of error code?
          > >
          > > --
          > > WWW: http://hardywang.1accesshost.com
          > > ICQ: 3359839
          > > yours Hardy
          > > "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com>[/color]
          > wrote[color=green]
          > > in message news:eWiePotdDH A.1532@TK2MSFTN GP10.phx.gbl...[color=darkred]
          > > > Hardy,
          > > >
          > > > If the return value is IntPtr.Zero, then throw a new instance of[/color][/color][/color]
          the[color=blue][color=green][color=darkred]
          > > > Win32Exception class. It will detail what the error from the call to
          > > > GetLastError is and it will give you more information about what went[/color]
          > > wrong[color=darkred]
          > > > with the call.
          > > >
          > > > Hope this helps.
          > > >
          > > >
          > > > --
          > > > - Nicholas Paldino [.NET/C# MVP]
          > > > - nicholas.paldin o@exisconsultin g.com
          > > >
          > > > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
          > > > news:Oo$9vktdDH A.2804@TK2MSFTN GP11.phx.gbl...
          > > > > Hi all:
          > > > > I read an article from
          > > > >
          > > >[/color]
          > >[/color]
          >[/color]
          http://www.c-sharpcorner.com/Code/20...mmatically.asp[color=blue][color=green][color=darkred]
          > > > > about how to install a windows service programmaticall y.
          > > > > Based ont the code sample, it provides the feature to install[/color]
          > > service[color=darkred]
          > > > > under LocalSystem account.
          > > > > What I need is to install service under some other certian[/color][/color]
          > account.[color=green]
          > > By[color=darkred]
          > > > > further studying the code, and MSDN
          > > > >
          > > >[/color]
          > >[/color]
          >[/color]
          (http://msdn.microsoft.com/library/de...-us/dllproc/ba[color=blue][color=green][color=darkred]
          > > > > se/createservice.a sp) ,
          > > > > public static extern IntPtr CreateService(I ntPtr[/color][/color][/color]
          SC_HANDLE,strin g[color=blue][color=green][color=darkred]
          > > > > lpSvcName,strin g lpDisplayName,
          > > > > int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
          > > > > dwErrorControl, string lpPathName,
          > > > > string lpLoadOrderGrou p,int lpdwTagId,strin g[/color]
          > > lpDependencies, string[color=darkred]
          > > > > lpServiceStartN ame,string lpPassword);
          > > > > is the core API to create a service. And the last two parameters[/color][/color]
          > should[color=green]
          > > be[color=darkred]
          > > > > name and password of account under wihcih service should run. But[/color][/color][/color]
          when[color=blue]
          > I[color=green][color=darkred]
          > > > > tried to pass values to these two parameters bu calling:
          > > > > sv_handle = CreateService(s c_handle, serviceName,[/color][/color][/color]
          serviceDisplayN ame,[color=blue][color=green][color=darkred]
          > > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
          > > > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
          > > > > servicePath, null, 0, null, _UserName, _Password);
          > > > > This piece of code is just a bit different from original, but[/color][/color]
          > sv_handle[color=green][color=darkred]
          > > > > return is 0, which means failure.
          > > > >
          > > > > Anybody has idea how to install a service under some certain[/color]
          > > account?[color=darkred]
          > > > >
          > > > >
          > > > > Thanks for any suggestion.
          > > > >
          > > > >
          > > > > --
          > > > > WWW: http://hardywang.1accesshost.com
          > > > > ICQ: 3359839
          > > > > yours Hardy
          > > > >
          > > > >
          > > >
          > > >[/color]
          > >
          > >[/color]
          >
          >[/color]


          Comment

          • Nicholas Paldino [.NET/C# MVP]

            #6
            Re: Installing a Windows Service Programmaticall y

            Hardy,

            Are you sure that this is the error that the call to CreateService gave?
            If you replace the "throw" part with a call to GetLastWin32Err or, what does
            that return?


            --
            - Nicholas Paldino [.NET/C# MVP]
            - nicholas.paldin o@exisconsultin g.com

            "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
            news:uuPxP2tdDH A.1712@tk2msftn gp13.phx.gbl...[color=blue]
            > I tried your codes, got error message "Control ID not found".
            >
            > --
            > WWW: http://hardywang.1accesshost.com
            > ICQ: 3359839
            > yours Hardy
            > "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com>[/color]
            wrote[color=blue]
            > in message news:e$jjjytdDH A.1448@TK2MSFTN GP12.phx.gbl...[color=green]
            > > Hardy,
            > >
            > > You should never call GetLastError yourself, as it is not guaranteed[/color]
            > to[color=green]
            > > be accurate. The reason for this is that the runtime makes API calls
            > > between your API call and it might set the error state on its own.[/color]
            > Because[color=green]
            > > of this, you should call the static GetLastWin32Err or method on the[/color]
            > Marshal[color=green]
            > > class.
            > >
            > > However, there is a class that does all of this, the Win32Exception
            > > class in the System.Componen tModel namespace. You should make your call
            > > like this:
            > >
            > > // Call CreateService.
            > > IntPtr sv_handle = CreateService(s c_handle, serviceName,[/color]
            > serviceDisplayN ame,[color=green]
            > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
            > > SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName, _Password);
            > >
            > > // Throw an exception if there is no handle.
            > > try
            > > {
            > > if (sv_handle == IntPtr.Zero)
            > > // Throw an exception.
            > > throw new Win32Exception( );
            > > }
            > > finally
            > > {
            > > CloseServiceHan dle(sc_handle);
            > > }
            > >
            > > This should give you the description of the error. You can also[/color][/color]
            look[color=blue]
            > in[color=green]
            > > WINERROR.H to find the error the code represents.
            > >
            > >
            > > --
            > > - Nicholas Paldino [.NET/C# MVP]
            > > - nicholas.paldin o@exisconsultin g.com
            > >
            > > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
            > > news:%23MNLettd DHA.1460@TK2MSF TNGP10.phx.gbl. ..[color=darkred]
            > > > I adding some code like:
            > > > sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
            > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
            > > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
            > > > servicePath, null, 0, null, _UserName, _Password);
            > > >
            > > > if (sv_handle.ToIn t32() == 0) {
            > > > CloseServiceHan dle(sc_handle);
            > > > int err = GetLastError();
            > > > return false;
            > > > }
            > > >
            > > > I tried to capture the error by reading return from GetLastError(), I[/color][/color]
            > got[color=green][color=darkred]
            > > > 997, where to find the definition of error code?
            > > >
            > > > --
            > > > WWW: http://hardywang.1accesshost.com
            > > > ICQ: 3359839
            > > > yours Hardy
            > > > "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com>[/color]
            > > wrote[color=darkred]
            > > > in message news:eWiePotdDH A.1532@TK2MSFTN GP10.phx.gbl...
            > > > > Hardy,
            > > > >
            > > > > If the return value is IntPtr.Zero, then throw a new instance of[/color][/color]
            > the[color=green][color=darkred]
            > > > > Win32Exception class. It will detail what the error from the call[/color][/color][/color]
            to[color=blue][color=green][color=darkred]
            > > > > GetLastError is and it will give you more information about what[/color][/color][/color]
            went[color=blue][color=green][color=darkred]
            > > > wrong
            > > > > with the call.
            > > > >
            > > > > Hope this helps.
            > > > >
            > > > >
            > > > > --
            > > > > - Nicholas Paldino [.NET/C# MVP]
            > > > > - nicholas.paldin o@exisconsultin g.com
            > > > >
            > > > > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
            > > > > news:Oo$9vktdDH A.2804@TK2MSFTN GP11.phx.gbl...
            > > > > > Hi all:
            > > > > > I read an article from
            > > > > >
            > > > >
            > > >[/color]
            > >[/color]
            >[/color]
            http://www.c-sharpcorner.com/Code/20...mmatically.asp[color=blue][color=green][color=darkred]
            > > > > > about how to install a windows service programmaticall y.
            > > > > > Based ont the code sample, it provides the feature to install
            > > > service
            > > > > > under LocalSystem account.
            > > > > > What I need is to install service under some other certian[/color]
            > > account.[color=darkred]
            > > > By
            > > > > > further studying the code, and MSDN
            > > > > >
            > > > >
            > > >[/color]
            > >[/color]
            >[/color]
            (http://msdn.microsoft.com/library/de...-us/dllproc/ba[color=blue][color=green][color=darkred]
            > > > > > se/createservice.a sp) ,
            > > > > > public static extern IntPtr CreateService(I ntPtr[/color][/color]
            > SC_HANDLE,strin g[color=green][color=darkred]
            > > > > > lpSvcName,strin g lpDisplayName,
            > > > > > int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
            > > > > > dwErrorControl, string lpPathName,
            > > > > > string lpLoadOrderGrou p,int lpdwTagId,strin g
            > > > lpDependencies, string
            > > > > > lpServiceStartN ame,string lpPassword);
            > > > > > is the core API to create a service. And the last two parameters[/color]
            > > should[color=darkred]
            > > > be
            > > > > > name and password of account under wihcih service should run. But[/color][/color]
            > when[color=green]
            > > I[color=darkred]
            > > > > > tried to pass values to these two parameters bu calling:
            > > > > > sv_handle = CreateService(s c_handle, serviceName,[/color][/color]
            > serviceDisplayN ame,[color=green][color=darkred]
            > > > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
            > > > > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
            > > > > > servicePath, null, 0, null, _UserName, _Password);
            > > > > > This piece of code is just a bit different from original, but[/color]
            > > sv_handle[color=darkred]
            > > > > > return is 0, which means failure.
            > > > > >
            > > > > > Anybody has idea how to install a service under some certain
            > > > account?
            > > > > >
            > > > > >
            > > > > > Thanks for any suggestion.
            > > > > >
            > > > > >
            > > > > > --
            > > > > > WWW: http://hardywang.1accesshost.com
            > > > > > ICQ: 3359839
            > > > > > yours Hardy
            > > > > >
            > > > > >
            > > > >
            > > > >
            > > >
            > > >[/color]
            > >
            > >[/color]
            >
            >[/color]


            Comment

            • Hardy Wang

              #7
              Re: Installing a Windows Service Programmaticall y

              Yes, I am sure, I used a catch to capure exception thrown by code, and got
              that message.
              By calling "int err = Marshal.GetLast Win32Error();" I have error number
              1421, don't know what does it mean.

              --
              WWW: http://hardywang.1accesshost.com
              ICQ: 3359839
              yours Hardy
              "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com> wrote
              in message news:eR3gh%23td DHA.1752@TK2MSF TNGP11.phx.gbl. ..[color=blue]
              > Hardy,
              >
              > Are you sure that this is the error that the call to CreateService[/color]
              gave?[color=blue]
              > If you replace the "throw" part with a call to GetLastWin32Err or, what[/color]
              does[color=blue]
              > that return?
              >
              >
              > --
              > - Nicholas Paldino [.NET/C# MVP]
              > - nicholas.paldin o@exisconsultin g.com
              >
              > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
              > news:uuPxP2tdDH A.1712@tk2msftn gp13.phx.gbl...[color=green]
              > > I tried your codes, got error message "Control ID not found".
              > >
              > > --
              > > WWW: http://hardywang.1accesshost.com
              > > ICQ: 3359839
              > > yours Hardy
              > > "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com>[/color]
              > wrote[color=green]
              > > in message news:e$jjjytdDH A.1448@TK2MSFTN GP12.phx.gbl...[color=darkred]
              > > > Hardy,
              > > >
              > > > You should never call GetLastError yourself, as it is not[/color][/color][/color]
              guaranteed[color=blue][color=green]
              > > to[color=darkred]
              > > > be accurate. The reason for this is that the runtime makes API calls
              > > > between your API call and it might set the error state on its own.[/color]
              > > Because[color=darkred]
              > > > of this, you should call the static GetLastWin32Err or method on the[/color]
              > > Marshal[color=darkred]
              > > > class.
              > > >
              > > > However, there is a class that does all of this, the[/color][/color][/color]
              Win32Exception[color=blue][color=green][color=darkred]
              > > > class in the System.Componen tModel namespace. You should make your[/color][/color][/color]
              call[color=blue][color=green][color=darkred]
              > > > like this:
              > > >
              > > > // Call CreateService.
              > > > IntPtr sv_handle = CreateService(s c_handle, serviceName,[/color]
              > > serviceDisplayN ame,[color=darkred]
              > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
              > > > SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName,[/color][/color][/color]
              _Password);[color=blue][color=green][color=darkred]
              > > >
              > > > // Throw an exception if there is no handle.
              > > > try
              > > > {
              > > > if (sv_handle == IntPtr.Zero)
              > > > // Throw an exception.
              > > > throw new Win32Exception( );
              > > > }
              > > > finally
              > > > {
              > > > CloseServiceHan dle(sc_handle);
              > > > }
              > > >
              > > > This should give you the description of the error. You can also[/color][/color]
              > look[color=green]
              > > in[color=darkred]
              > > > WINERROR.H to find the error the code represents.
              > > >
              > > >
              > > > --
              > > > - Nicholas Paldino [.NET/C# MVP]
              > > > - nicholas.paldin o@exisconsultin g.com
              > > >
              > > > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
              > > > news:%23MNLettd DHA.1460@TK2MSF TNGP10.phx.gbl. ..
              > > > > I adding some code like:
              > > > > sv_handle = CreateService(s c_handle, serviceName,[/color][/color][/color]
              serviceDisplayN ame,[color=blue][color=green][color=darkred]
              > > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
              > > > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
              > > > > servicePath, null, 0, null, _UserName, _Password);
              > > > >
              > > > > if (sv_handle.ToIn t32() == 0) {
              > > > > CloseServiceHan dle(sc_handle);
              > > > > int err = GetLastError();
              > > > > return false;
              > > > > }
              > > > >
              > > > > I tried to capture the error by reading return from GetLastError(),[/color][/color][/color]
              I[color=blue][color=green]
              > > got[color=darkred]
              > > > > 997, where to find the definition of error code?
              > > > >
              > > > > --
              > > > > WWW: http://hardywang.1accesshost.com
              > > > > ICQ: 3359839
              > > > > yours Hardy
              > > > > "Nicholas Paldino [.NET/C# MVP]"[/color][/color][/color]
              <nicholas.paldi no@exisconsulti ng.com>[color=blue][color=green][color=darkred]
              > > > wrote
              > > > > in message news:eWiePotdDH A.1532@TK2MSFTN GP10.phx.gbl...
              > > > > > Hardy,
              > > > > >
              > > > > > If the return value is IntPtr.Zero, then throw a new instance[/color][/color][/color]
              of[color=blue][color=green]
              > > the[color=darkred]
              > > > > > Win32Exception class. It will detail what the error from the call[/color][/color]
              > to[color=green][color=darkred]
              > > > > > GetLastError is and it will give you more information about what[/color][/color]
              > went[color=green][color=darkred]
              > > > > wrong
              > > > > > with the call.
              > > > > >
              > > > > > Hope this helps.
              > > > > >
              > > > > >
              > > > > > --
              > > > > > - Nicholas Paldino [.NET/C# MVP]
              > > > > > - nicholas.paldin o@exisconsultin g.com
              > > > > >
              > > > > > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
              > > > > > news:Oo$9vktdDH A.2804@TK2MSFTN GP11.phx.gbl...
              > > > > > > Hi all:
              > > > > > > I read an article from
              > > > > > >
              > > > > >
              > > > >
              > > >[/color]
              > >[/color]
              >[/color]
              http://www.c-sharpcorner.com/Code/20...mmatically.asp[color=blue][color=green][color=darkred]
              > > > > > > about how to install a windows service programmaticall y.
              > > > > > > Based ont the code sample, it provides the feature to[/color][/color][/color]
              install[color=blue][color=green][color=darkred]
              > > > > service
              > > > > > > under LocalSystem account.
              > > > > > > What I need is to install service under some other certian
              > > > account.
              > > > > By
              > > > > > > further studying the code, and MSDN
              > > > > > >
              > > > > >
              > > > >
              > > >[/color]
              > >[/color]
              >[/color]
              (http://msdn.microsoft.com/library/de...-us/dllproc/ba[color=blue][color=green][color=darkred]
              > > > > > > se/createservice.a sp) ,
              > > > > > > public static extern IntPtr CreateService(I ntPtr[/color]
              > > SC_HANDLE,strin g[color=darkred]
              > > > > > > lpSvcName,strin g lpDisplayName,
              > > > > > > int dwDesiredAccess ,int dwServiceType,i nt[/color][/color][/color]
              dwStartType,int[color=blue][color=green][color=darkred]
              > > > > > > dwErrorControl, string lpPathName,
              > > > > > > string lpLoadOrderGrou p,int lpdwTagId,strin g
              > > > > lpDependencies, string
              > > > > > > lpServiceStartN ame,string lpPassword);
              > > > > > > is the core API to create a service. And the last two parameters
              > > > should
              > > > > be
              > > > > > > name and password of account under wihcih service should run.[/color][/color][/color]
              But[color=blue][color=green]
              > > when[color=darkred]
              > > > I
              > > > > > > tried to pass values to these two parameters bu calling:
              > > > > > > sv_handle = CreateService(s c_handle, serviceName,[/color]
              > > serviceDisplayN ame,[color=darkred]
              > > > > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
              > > > > > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
              > > > > > > servicePath, null, 0, null, _UserName, _Password);
              > > > > > > This piece of code is just a bit different from original, but
              > > > sv_handle
              > > > > > > return is 0, which means failure.
              > > > > > >
              > > > > > > Anybody has idea how to install a service under some certain
              > > > > account?
              > > > > > >
              > > > > > >
              > > > > > > Thanks for any suggestion.
              > > > > > >
              > > > > > >
              > > > > > > --
              > > > > > > WWW: http://hardywang.1accesshost.com
              > > > > > > ICQ: 3359839
              > > > > > > yours Hardy
              > > > > > >
              > > > > > >
              > > > > >
              > > > > >
              > > > >
              > > > >
              > > >
              > > >[/color]
              > >
              > >[/color]
              >
              >[/color]


              Comment

              • Nicholas Paldino [.NET/C# MVP]

                #8
                Re: Installing a Windows Service Programmaticall y

                Hardy,

                This is truly odd. 1421 is what the exception and the call to
                GetLastWin32Err or returned. However, I don't know why CreateService is
                returning it. What are you doing in the UI when this call is made?


                --
                - Nicholas Paldino [.NET/C# MVP]
                - nicholas.paldin o@exisconsultin g.com

                "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
                news:e7iUSCudDH A.1580@tk2msftn gp13.phx.gbl...[color=blue]
                > Yes, I am sure, I used a catch to capure exception thrown by code, and got
                > that message.
                > By calling "int err = Marshal.GetLast Win32Error();" I have error number
                > 1421, don't know what does it mean.
                >
                > --
                > WWW: http://hardywang.1accesshost.com
                > ICQ: 3359839
                > yours Hardy
                > "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com>[/color]
                wrote[color=blue]
                > in message news:eR3gh%23td DHA.1752@TK2MSF TNGP11.phx.gbl. ..[color=green]
                > > Hardy,
                > >
                > > Are you sure that this is the error that the call to CreateService[/color]
                > gave?[color=green]
                > > If you replace the "throw" part with a call to GetLastWin32Err or, what[/color]
                > does[color=green]
                > > that return?
                > >
                > >
                > > --
                > > - Nicholas Paldino [.NET/C# MVP]
                > > - nicholas.paldin o@exisconsultin g.com
                > >
                > > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
                > > news:uuPxP2tdDH A.1712@tk2msftn gp13.phx.gbl...[color=darkred]
                > > > I tried your codes, got error message "Control ID not found".
                > > >
                > > > --
                > > > WWW: http://hardywang.1accesshost.com
                > > > ICQ: 3359839
                > > > yours Hardy
                > > > "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com>[/color]
                > > wrote[color=darkred]
                > > > in message news:e$jjjytdDH A.1448@TK2MSFTN GP12.phx.gbl...
                > > > > Hardy,
                > > > >
                > > > > You should never call GetLastError yourself, as it is not[/color][/color]
                > guaranteed[color=green][color=darkred]
                > > > to
                > > > > be accurate. The reason for this is that the runtime makes API[/color][/color][/color]
                calls[color=blue][color=green][color=darkred]
                > > > > between your API call and it might set the error state on its own.
                > > > Because
                > > > > of this, you should call the static GetLastWin32Err or method on the
                > > > Marshal
                > > > > class.
                > > > >
                > > > > However, there is a class that does all of this, the[/color][/color]
                > Win32Exception[color=green][color=darkred]
                > > > > class in the System.Componen tModel namespace. You should make your[/color][/color]
                > call[color=green][color=darkred]
                > > > > like this:
                > > > >
                > > > > // Call CreateService.
                > > > > IntPtr sv_handle = CreateService(s c_handle, serviceName,
                > > > serviceDisplayN ame,
                > > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS, SERVICE_AUTO_ST ART,
                > > > > SERVICE_ERROR_N ORMAL, servicePath, null, 0, null, _UserName,[/color][/color]
                > _Password);[color=green][color=darkred]
                > > > >
                > > > > // Throw an exception if there is no handle.
                > > > > try
                > > > > {
                > > > > if (sv_handle == IntPtr.Zero)
                > > > > // Throw an exception.
                > > > > throw new Win32Exception( );
                > > > > }
                > > > > finally
                > > > > {
                > > > > CloseServiceHan dle(sc_handle);
                > > > > }
                > > > >
                > > > > This should give you the description of the error. You can also[/color]
                > > look[color=darkred]
                > > > in
                > > > > WINERROR.H to find the error the code represents.
                > > > >
                > > > >
                > > > > --
                > > > > - Nicholas Paldino [.NET/C# MVP]
                > > > > - nicholas.paldin o@exisconsultin g.com
                > > > >
                > > > > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
                > > > > news:%23MNLettd DHA.1460@TK2MSF TNGP10.phx.gbl. ..
                > > > > > I adding some code like:
                > > > > > sv_handle = CreateService(s c_handle, serviceName,[/color][/color]
                > serviceDisplayN ame,[color=green][color=darkred]
                > > > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
                > > > > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
                > > > > > servicePath, null, 0, null, _UserName, _Password);
                > > > > >
                > > > > > if (sv_handle.ToIn t32() == 0) {
                > > > > > CloseServiceHan dle(sc_handle);
                > > > > > int err = GetLastError();
                > > > > > return false;
                > > > > > }
                > > > > >
                > > > > > I tried to capture the error by reading return from[/color][/color][/color]
                GetLastError(),[color=blue]
                > I[color=green][color=darkred]
                > > > got
                > > > > > 997, where to find the definition of error code?
                > > > > >
                > > > > > --
                > > > > > WWW: http://hardywang.1accesshost.com
                > > > > > ICQ: 3359839
                > > > > > yours Hardy
                > > > > > "Nicholas Paldino [.NET/C# MVP]"[/color][/color]
                > <nicholas.paldi no@exisconsulti ng.com>[color=green][color=darkred]
                > > > > wrote
                > > > > > in message news:eWiePotdDH A.1532@TK2MSFTN GP10.phx.gbl...
                > > > > > > Hardy,
                > > > > > >
                > > > > > > If the return value is IntPtr.Zero, then throw a new[/color][/color][/color]
                instance[color=blue]
                > of[color=green][color=darkred]
                > > > the
                > > > > > > Win32Exception class. It will detail what the error from the[/color][/color][/color]
                call[color=blue][color=green]
                > > to[color=darkred]
                > > > > > > GetLastError is and it will give you more information about what[/color]
                > > went[color=darkred]
                > > > > > wrong
                > > > > > > with the call.
                > > > > > >
                > > > > > > Hope this helps.
                > > > > > >
                > > > > > >
                > > > > > > --
                > > > > > > - Nicholas Paldino [.NET/C# MVP]
                > > > > > > - nicholas.paldin o@exisconsultin g.com
                > > > > > >
                > > > > > > "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message
                > > > > > > news:Oo$9vktdDH A.2804@TK2MSFTN GP11.phx.gbl...
                > > > > > > > Hi all:
                > > > > > > > I read an article from
                > > > > > > >
                > > > > > >
                > > > > >
                > > > >
                > > >[/color]
                > >[/color]
                >[/color]
                http://www.c-sharpcorner.com/Code/20...mmatically.asp[color=blue][color=green][color=darkred]
                > > > > > > > about how to install a windows service programmaticall y.
                > > > > > > > Based ont the code sample, it provides the feature to[/color][/color]
                > install[color=green][color=darkred]
                > > > > > service
                > > > > > > > under LocalSystem account.
                > > > > > > > What I need is to install service under some other certian
                > > > > account.
                > > > > > By
                > > > > > > > further studying the code, and MSDN
                > > > > > > >
                > > > > > >
                > > > > >
                > > > >
                > > >[/color]
                > >[/color]
                >[/color]
                (http://msdn.microsoft.com/library/de...-us/dllproc/ba[color=blue][color=green][color=darkred]
                > > > > > > > se/createservice.a sp) ,
                > > > > > > > public static extern IntPtr CreateService(I ntPtr
                > > > SC_HANDLE,strin g
                > > > > > > > lpSvcName,strin g lpDisplayName,
                > > > > > > > int dwDesiredAccess ,int dwServiceType,i nt[/color][/color]
                > dwStartType,int[color=green][color=darkred]
                > > > > > > > dwErrorControl, string lpPathName,
                > > > > > > > string lpLoadOrderGrou p,int lpdwTagId,strin g
                > > > > > lpDependencies, string
                > > > > > > > lpServiceStartN ame,string lpPassword);
                > > > > > > > is the core API to create a service. And the last two[/color][/color][/color]
                parameters[color=blue][color=green][color=darkred]
                > > > > should
                > > > > > be
                > > > > > > > name and password of account under wihcih service should run.[/color][/color]
                > But[color=green][color=darkred]
                > > > when
                > > > > I
                > > > > > > > tried to pass values to these two parameters bu calling:
                > > > > > > > sv_handle = CreateService(s c_handle, serviceName,
                > > > serviceDisplayN ame,
                > > > > > > > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
                > > > > > > > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
                > > > > > > > servicePath, null, 0, null, _UserName, _Password);
                > > > > > > > This piece of code is just a bit different from original, but
                > > > > sv_handle
                > > > > > > > return is 0, which means failure.
                > > > > > > >
                > > > > > > > Anybody has idea how to install a service under some[/color][/color][/color]
                certain[color=blue][color=green][color=darkred]
                > > > > > account?
                > > > > > > >
                > > > > > > >
                > > > > > > > Thanks for any suggestion.
                > > > > > > >
                > > > > > > >
                > > > > > > > --
                > > > > > > > WWW: http://hardywang.1accesshost.com
                > > > > > > > ICQ: 3359839
                > > > > > > > yours Hardy
                > > > > > > >
                > > > > > > >
                > > > > > >
                > > > > > >
                > > > > >
                > > > > >
                > > > >
                > > > >
                > > >
                > > >[/color]
                > >
                > >[/color]
                >
                >[/color]


                Comment

                • Hardy Wang

                  #9
                  Re: Installing a Windows Service Programmaticall y

                  Let me post all my codes here, what I like to do is to create a class
                  library, I can use it by other UI, then add a test Windows Application
                  Class Library:
                  ----------------------------------------
                  using System;
                  using System.Runtime. InteropServices ;

                  /// <summary>
                  /// Programmaticall y install / uninstall Windows Service
                  /// </summary>
                  /// <example>
                  /// <code>
                  /// string svcPath = @"C:\build\serv ice\Debug\Servi ce.exe";
                  /// string svcDispName="Se rvice Display Name";
                  /// string svcName= "Service Name";
                  /// WindowsServiceI nstaller c = new WindowsServiceI nstaller();
                  /// c.InstallServic e(svcPath, svcName, svcDispName);
                  /// </code>
                  /// </example>
                  public class WindowsServiceI nstaller {
                  /// <summary>
                  /// Default constructor to initialize instance
                  /// </summary>
                  public WindowsServiceI nstaller() {
                  _UserName = "";
                  _Password = "";
                  }

                  /// <summary>
                  /// Username to run account
                  /// </summary>
                  private string _UserName;
                  /// <summary>
                  /// Password to run account
                  /// </summary>
                  private string _Password;

                  #region DLLImport
                  /// <summary>
                  /// Open SC Manager
                  /// </summary>
                  [DllImport("adva pi32.dll")]
                  private static extern IntPtr OpenSCManager(s tring lpMachineName,s tring
                  lpSCDB, int scParameter);
                  /// <summary>
                  /// Create Service
                  /// </summary>
                  [DllImport("Adva pi32.dll")]
                  private static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
                  lpSvcName,strin g lpDisplayName,
                  int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
                  dwErrorControl, string lpPathName,
                  string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string
                  lpServiceStartN ame,string lpPassword);
                  /// <summary>
                  /// Close Service Handle
                  /// </summary>
                  [DllImport("adva pi32.dll")]
                  private static extern void CloseServiceHan dle(IntPtr SCHANDLE);
                  /// <summary>
                  /// Start Service
                  /// </summary>
                  [DllImport("adva pi32.dll")]
                  private static extern int StartService(In tPtr SVHANDLE,int
                  dwNumServiceArg s,string lpServiceArgVec tors);
                  /// <summary>
                  /// Open Service
                  /// </summary>
                  [DllImport("adva pi32.dll",SetLa stError=true)]
                  private static extern IntPtr OpenService(Int Ptr SCHANDLE,string
                  lpSvcName,int dwNumServiceArg s);
                  /// <summary>
                  /// Delete Service
                  /// </summary>
                  [DllImport("adva pi32.dll")]
                  private static extern int DeleteService(I ntPtr SVHANDLE);

                  /// <summary>
                  /// Get last error
                  /// </summary>
                  [DllImport("kern el32.dll")]
                  private static extern int GetLastError();
                  #endregion DLLImport

                  //path to the service that you want to install
                  //servicePath = @"C:\build\serv ice\Debug\Servi ce.exe";
                  //serviceDisplayN ame="Service Display Name";
                  //serviceName= "Service Name";

                  /// <summary>
                  /// This method installs and runs the service in the service conrol manager
                  under LocalSystem account.
                  /// </summary>
                  /// <param name="servicePa th">The complete path of the service.</param>
                  /// <param name="serviceNa me">Name of the service.</param>
                  /// <param name="serviceDi splayName">Disp lay name of the service.</param>
                  /// <returns>True if the process went throgh successfully. False if there
                  was any error.</returns>
                  public bool InstallService( string servicePath, string serviceName, string
                  serviceDisplayN ame) {
                  #region Constants declaration.
                  int SC_MANAGER_CREA TE_SERVICE = 0x0002;
                  int SERVICE_WIN32_O WN_PROCESS = 0x00000010;
                  int SERVICE_DEMAND_ START = 0x00000003;
                  int SERVICE_ERROR_N ORMAL = 0x00000001;

                  int STANDARD_RIGHTS _REQUIRED = 0xF0000;
                  int SERVICE_QUERY_C ONFIG = 0x0001;
                  int SERVICE_CHANGE_ CONFIG = 0x0002;
                  int SERVICE_QUERY_S TATUS = 0x0004;
                  int SERVICE_ENUMERA TE_DEPENDENTS = 0x0008;
                  int SERVICE_START = 0x0010;
                  int SERVICE_STOP = 0x0020;
                  int SERVICE_PAUSE_C ONTINUE =0x0040;
                  int SERVICE_INTERRO GATE = 0x0080;
                  int SERVICE_USER_DE FINED_CONTROL = 0x0100;

                  int SERVICE_ALL_ACC ESS = (STANDARD_RIGHT S_REQUIRED |
                  SERVICE_QUERY_C ONFIG |
                  SERVICE_CHANGE_ CONFIG |
                  SERVICE_QUERY_S TATUS |
                  SERVICE_ENUMERA TE_DEPENDENTS |
                  SERVICE_START |
                  SERVICE_STOP |
                  SERVICE_PAUSE_C ONTINUE |
                  SERVICE_INTERRO GATE |
                  SERVICE_USER_DE FINED_CONTROL);
                  int SERVICE_AUTO_ST ART = 0x00000002;
                  #endregion Constants declaration.

                  IntPtr sc_handle = OpenSCManager(n ull,null,SC_MAN AGER_CREATE_SER VICE);

                  if (sc_handle.ToIn t32() != 0) {
                  IntPtr sv_handle;
                  if (_UserName.Trim ().Length > 0) {
                  sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
                  SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
                  SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
                  servicePath, null, 0, null, _UserName, _Password);
                  } else {
                  sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
                  SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
                  SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
                  servicePath, null, 0, null, null, null);
                  }

                  if (sv_handle.ToIn t32() == 0) {
                  int err = Marshal.GetLast Win32Error();
                  CloseServiceHan dle(sc_handle);
                  return false;
                  } else {
                  //now trying to start the service
                  int i = StartService(sv _handle, 0, null);
                  // If the value i is zero, then there was an error starting the service.
                  // note: error may arise if the service is already running or some other
                  problem.
                  if(i == 0) {
                  //Console.WriteLi ne("Couldnt start service");
                  return false;
                  }
                  //Console.WriteLi ne("Success");
                  CloseServiceHan dle(sc_handle);
                  return true;
                  }
                  } else {
                  //Console.WriteLi ne("SCM not opened successfully");
                  return false;
                  }
                  }

                  /// <summary>
                  /// This method installs and runs the service in the service conrol manager
                  under specified account.
                  /// </summary>
                  /// <param name="servicePa th">The complete path of the service.</param>
                  /// <param name="serviceNa me">Name of the service.</param>
                  /// <param name="serviceDi splayName">Disp lay name of the service.</param>
                  /// <param name="serviceSt artName">The name of the account under which the
                  service should run</param>
                  /// <param name="password" >The password to the account name specified by
                  the serviceStartNam e parameter</param>
                  /// <returns>True if the process went throgh successfully. False if there
                  was any error.</returns>
                  public bool InstallService( string servicePath, string serviceName,
                  string serviceDisplayN ame, string serviceStartNam e, string password) {
                  _UserName = serviceStartNam e;
                  _Password = password;

                  return InstallService( servicePath, serviceName, serviceDisplayN ame);
                  }

                  /// <summary>
                  /// This method uninstalls the service from the service conrol manager.
                  /// </summary>
                  /// <param name="serviceNa me">Name of the service to uninstall.</param>
                  public bool UnInstallServic e(string serviceName) {
                  int GENERIC_WRITE = 0x40000000;
                  IntPtr sc_hndl = OpenSCManager(n ull,null,GENERI C_WRITE);

                  if (sc_hndl.ToInt3 2() !=0) {
                  int DELETE = 0x10000;
                  IntPtr svc_hndl = OpenService(sc_ hndl,serviceNam e,DELETE);
                  //Console.WriteLi ne(svc_hndl.ToI nt32());
                  if(svc_hndl.ToI nt32() !=0) {
                  int i = DeleteService(s vc_hndl);
                  if (i != 0) {
                  CloseServiceHan dle(sc_hndl);
                  return true;
                  } else {
                  CloseServiceHan dle(sc_hndl);
                  return false;
                  }
                  } else {
                  return false;
                  }
                  } else {
                  return false;
                  }
                  }
                  }
                  =============== ============
                  Test application:
                  -----------------------------
                  private void button1_Click(o bject sender, System.EventArg s e) {
                  WindowsServiceI nstaller c = new WindowsServiceI nstaller();
                  if
                  (c.InstallServi ce(@"C:\Work\Re portScheduler\R eportScheduler\ bin\Debug\Repor t
                  Scheduler.exe", "Report", "Report", @"domian\userna me", "password") ) {
                  MessageBox.Show ("OK");
                  } else {
                  MessageBox.Show ("Bad");
                  }
                  }
                  =============== =============== =============== ==
                  I tried the overload without username and password, the service is created,
                  but this one failed.


                  Comment

                  • Willy Denoyette [MVP]

                    #10
                    Re: Installing a Windows Service Programmaticall y

                    Why not simply use the sc.exe commandline utility (standard on XP and W2K3, resource kit utility for NT4).

                    Willy.

                    "Hardy Wang" <hardy_wang@mar ketrend.com> wrote in message news:Oo$9vktdDH A.2804@TK2MSFTN GP11.phx.gbl...[color=blue]
                    > Hi all:
                    > I read an article from
                    > http://www.c-sharpcorner.com/Code/20...mmatically.asp
                    > about how to install a windows service programmaticall y.
                    > Based ont the code sample, it provides the feature to install service
                    > under LocalSystem account.
                    > What I need is to install service under some other certian account. By
                    > further studying the code, and MSDN
                    > (http://msdn.microsoft.com/library/de...-us/dllproc/ba
                    > se/createservice.a sp) ,
                    > public static extern IntPtr CreateService(I ntPtr SC_HANDLE,strin g
                    > lpSvcName,strin g lpDisplayName,
                    > int dwDesiredAccess ,int dwServiceType,i nt dwStartType,int
                    > dwErrorControl, string lpPathName,
                    > string lpLoadOrderGrou p,int lpdwTagId,strin g lpDependencies, string
                    > lpServiceStartN ame,string lpPassword);
                    > is the core API to create a service. And the last two parameters should be
                    > name and password of account under wihcih service should run. But when I
                    > tried to pass values to these two parameters bu calling:
                    > sv_handle = CreateService(s c_handle, serviceName, serviceDisplayN ame,
                    > SERVICE_ALL_ACC ESS, SERVICE_WIN32_O WN_PROCESS,
                    > SERVICE_AUTO_ST ART, SERVICE_ERROR_N ORMAL,
                    > servicePath, null, 0, null, _UserName, _Password);
                    > This piece of code is just a bit different from original, but sv_handle
                    > return is 0, which means failure.
                    >
                    > Anybody has idea how to install a service under some certain account?
                    >
                    >
                    > Thanks for any suggestion.
                    >
                    >
                    > --
                    > WWW: http://hardywang.1accesshost.com
                    > ICQ: 3359839
                    > yours Hardy
                    >
                    >[/color]


                    Comment

                    Working...