Service.ServiceEx.SetCommandLineArgs C# (CSharp) Method

SetCommandLineArgs() public static method

public static SetCommandLineArgs ( string serviceName, string parameters ) : void
serviceName string
parameters string
return void
        public static void SetCommandLineArgs(string serviceName, string parameters)
        {
            IntPtr hScm = OpenSCManager(null, null, SC_MANAGER_ALL_ACCESS);
            if (hScm == IntPtr.Zero)
                throw new Win32Exception();
            try
            {
                IntPtr hSvc = OpenService(hScm, serviceName, SERVICE_ALL_ACCESS);
                if (hSvc == IntPtr.Zero)
                    throw new Win32Exception();
                try
                {
                    QUERY_SERVICE_CONFIG oldConfig;
                    uint bytesAllocated = 8192; // Per documentation, 8K is max size.
                    IntPtr ptr = Marshal.AllocHGlobal((int)bytesAllocated);
                    try
                    {
                        uint bytesNeeded;
                        if (!QueryServiceConfig(hSvc, ptr, bytesAllocated, out bytesNeeded))
                        {
                            throw new Win32Exception();
                        }
                        oldConfig = (QUERY_SERVICE_CONFIG)Marshal.PtrToStructure(ptr, typeof(QUERY_SERVICE_CONFIG));
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(ptr);
                    }

                    string newBinaryPathAndParameters = oldConfig.lpBinaryPathName + " " + parameters;

                    if (!ChangeServiceConfig(hSvc, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE, SERVICE_NO_CHANGE,
                        newBinaryPathAndParameters, null, IntPtr.Zero, null, null, null, null))
                        throw new Win32Exception();
                }
                finally
                {
                    if (!CloseServiceHandle(hSvc))
                        throw new Win32Exception();
                }
            }
            finally
            {
                if (!CloseServiceHandle(hScm))
                    throw new Win32Exception();
            }
        }

Usage Example

Example #1
0
        public override void Install(IDictionary stateSaver)
        {
            this.Uninstall(stateSaver);

            var serviceSubname = stateSaver["subName"] as string;

            base.Install(stateSaver);
            ServiceEx.SetCommandLineArgs(Service1.GetServiceName(serviceSubname), serviceSubname);

            using (var sc = new ServiceController(Service1.GetServiceName(serviceSubname)))
            {
                sc.Start();
                sc.Refresh();
            }
        }