コード例 #1
0
            public static void InstallService(
                [Argument("serviceName", Description = "The service name to install as.")] string svcName,
                [Argument("displayName", Description = "The display name of the service.")] string displayName,
                [Argument("startupType", Description = "The service startup type: Automatic, Manual, or Disabled.")] ServiceStartMode startupType,
                [Argument("serviceAccount", Description = "The service account: LocalService, NetworkService, or LocalSystem.")] ServiceAccount serviceAccount,
                [Argument("command", Description = "The command to run as a service.")] string commandName,
                [Argument("arguments", DefaultValue = null, Description = "The arguments required to run the command.")] string[] arguments,
                ICommandInterpreter ci,
                [Argument("executable", Visible = false), System.ComponentModel.DefaultValue(null)]
                string executable
                )
            {
                ICommand cmd;

                if (!ci.TryGetCommand("RunAsService", out cmd))
                {
                    throw new ApplicationException(
                              "You must add typeof(ServiceCommands) to the commands or provide your own RunAsService command.");
                }
                if (!ci.TryGetCommand(commandName, out cmd))
                {
                    throw new ApplicationException("The command name '" + commandName + "' was not found.");
                }
                if (String.IsNullOrEmpty(svcName))
                {
                    throw new ArgumentNullException("svcName");
                }

                string        exe  = Path.GetFullPath(executable ?? new Uri(Constants.EntryAssembly.Location).AbsolutePath);
                List <string> args = new List <string>();

                args.Add("RunAsService");
                args.Add("/serviceName=" + svcName);
                args.Add(commandName);
                args.AddRange(arguments ?? new string[0]);

                using (
                    SvcControlManager scm = SvcControlManager.Create(svcName, displayName, false, startupType, exe,
                                                                     args.ToArray(),
                                                                     SvcControlManager.NT_AUTHORITY.Account(
                                                                         serviceAccount), null))
                {
                    args.RemoveRange(0, 2);
                    args.Insert(0, Path.GetFileName(exe));
                    scm.SetDescription(ArgumentList.EscapeArguments(args.ToArray()));
                }
            }