我有类似的要求,不幸的是,将命令行参数存储在文件中不是一种选择。
免责声明:此方法仅适用于 Windows
首先我添加了一个安装后操作
x.AfterInstall(
installSettings =>
{
AddCommandLineParametersToStartupOptions(installSettings);
});
在AddCommanLineParameterToStartupOptions
我更新服务的ImagePath Windows 注册表项以包含命令行参数。
TopShelf 在此步骤之后添加它的参数,以避免重复,servicename
我instance
将它们过滤掉。您可能想要过滤掉的不仅仅是那些,但在我的情况下这已经足够了。
private static void AddCommandLineParametersToStartupOptions(InstallHostSettings installSettings)
{
var serviceKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(
$"SYSTEM\\CurrentControlSet\\Services\\{installSettings.ServiceName}",
true);
if (serviceKey == null)
{
throw new Exception($"Could not locate Registry Key for service '{installSettings.ServiceName}'");
}
var arguments = Environment.GetCommandLineArgs();
string programName = null;
StringBuilder argumentsList = new StringBuilder();
for (int i = 0; i < arguments.Length; i++)
{
if (i == 0)
{
// program name is the first argument
programName = arguments[i];
}
else
{
// Remove these servicename and instance arguments as TopShelf adds them as well
// Remove install switch
if (arguments[i].StartsWith("-servicename", StringComparison.InvariantCultureIgnoreCase) |
arguments[i].StartsWith("-instance", StringComparison.InvariantCultureIgnoreCase) |
arguments[i].StartsWith("install", StringComparison.InvariantCultureIgnoreCase))
{
continue;
}
argumentsList.Append(" ");
argumentsList.Append(arguments[i]);
}
}
// Apply the arguments to the ImagePath value under the service Registry key
var imageName = $"\"{Environment.CurrentDirectory}\\{programName}\" {argumentsList.ToString()}";
serviceKey.SetValue("ImagePath", imageName, Microsoft.Win32.RegistryValueKind.String);
}