Beispiel #1
0
        public void SetWindowsServiceCredentials(string serviceName, string username, string password)
        {
            IntPtr hManager = IntPtr.Zero;
            IntPtr hService = IntPtr.Zero;

            try
            {
                hManager = ServiceWrapper.OpenSCManager(null, null, ServiceWrapper.SC_MANAGER_ALL_ACCESS);
                if (hManager == IntPtr.Zero)
                {
                    ThrowWin32Exception();
                }
                hService = ServiceWrapper.OpenService(hManager, serviceName, ServiceWrapper.SERVICE_QUERY_CONFIG | ServiceWrapper.SERVICE_CHANGE_CONFIG);
                if (hService == IntPtr.Zero)
                {
                    ThrowWin32Exception();
                }

                if (!ServiceWrapper.ChangeServiceConfig(hService, ServiceWrapper.SERVICE_NO_CHANGE, ServiceWrapper.SERVICE_NO_CHANGE, ServiceWrapper.SERVICE_NO_CHANGE, null, null, IntPtr.Zero, null, username, password, null))
                {
                    ThrowWin32Exception();
                }
            }
            finally
            {
                if (hService != IntPtr.Zero)
                {
                    ServiceWrapper.CloseServiceHandle(hService);
                }
                if (hManager != IntPtr.Zero)
                {
                    ServiceWrapper.CloseServiceHandle(hManager);
                }
            }
        }