Created
March 22, 2018 15:35
-
-
Save sm-g/77e73efab4177794533d8e0589214715 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/questions/15245770/how-to-specify-command-line-options-for-service-in-topshelf/36044058#36044058 | |
/// <param name="argsToSave"> | |
/// If empty, all cli arguments, except added by TopShelf itself, included. | |
/// If not empty, only arguments starting with string from that array included. | |
/// </param> | |
public static void AddCommandLineParametersToStartupOptions(this InstallHostSettings installSettings, IReadOnlyCollection<string> argsToSave = null) | |
{ | |
var serviceKey = Registry.LocalMachine.OpenSubKey( | |
$"SYSTEM\\CurrentControlSet\\Services\\{installSettings.ServiceName}", | |
true); | |
if (serviceKey == null) | |
throw new InvalidOperationException($"Could not locate Registry Key for service '{installSettings.ServiceName}'"); | |
var arguments = Environment.GetCommandLineArgs(); | |
if (arguments.Length == 0) | |
throw new InvalidOperationException("Arguments should contain at least one element - path to exe"); | |
var exePath = Path.GetFullPath(arguments[0]); | |
var filter = argsToSave == null | |
? (Func<string, bool>)isNotAddedByTopshelfArgument | |
: isInArgsToSave; | |
var argumentsList = string.Join(" ", arguments.Skip(1).Where(filter)); | |
var imagePath = $"\"{exePath}\" {argumentsList}"; | |
serviceKey.SetValue("ImagePath", imagePath, RegistryValueKind.String); | |
// servicename and instance arguments added by Topshelf https://github.com/Topshelf/Topshelf/blob/develop/src/Topshelf/Runtime/Windows/HostServiceInstaller.cs#L132 | |
// also remove `install` verb | |
bool isNotAddedByTopshelfArgument(string arg) => !( | |
arg.StartsWith("-servicename", StringComparison.OrdinalIgnoreCase) || | |
arg.StartsWith("-instance", StringComparison.OrdinalIgnoreCase) || | |
arg.StartsWith("install", StringComparison.OrdinalIgnoreCase)); | |
bool isInArgsToSave(string arg) => argsToSave.Any(z => arg.StartsWith($"-{z}", StringComparison.OrdinalIgnoreCase)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment