Windows Service 啟動參數

Windows Service可以透過幾種方式來傳入啟動參數
可以利用服務的啟動參數


OnStart就可以收到參數

但需要注意這種方式只能設定一次,下次啟動還要再設定才行
透過命令列的話有兩種方式
net start service1 /3000 /yyyyMMddHHmmss
但這種方式收到的參數也會有斜線

sc start service1 3000 yyyyMMddHHmmss
這種方式就不會有斜線了

還有一種方式是設定在服務機碼的ImagePath後面
需要透過覆寫安裝程式的Install函式來完成
using System.Collections;
using System.ComponentModel;
using Microsoft.Win32;

namespace MyService
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
public ProjectInstaller()
{
InitializeComponent();
}

public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);

// 安裝的時後增加啟動參數
RegistryKey System = Registry.LocalMachine.OpenSubKey(“System”);
RegistryKey currentControlSet = System.OpenSubKey(“CurrentControlSet”);
RegistryKey services = currentControlSet.OpenSubKey(“Services”);
RegistryKey service = services.OpenSubKey(this.serviceInstaller1.ServiceName, true);
string imagePath = service.GetValue(“ImagePath”) + “ 3000 yyyyMMddHHmmss”;
service.SetValue(“ImagePath”, imagePath);
service.Close();
}
}
}


服務的內容就會在執行路徑後面帶上參數
透過Environment.GetCommandLineArgs()來取得參數

只不過這種參數方式是需要修改機碼,所以設定上不太方便

最簡單好用的方式,莫過於透過app.config中的appSettings
<?xml version=”1.0” encoding=”utf-8”?>
<configuration>
<configSections>
<sectionGroup name=”common”>
<section name=”logging” type=”Common.Logging.ConfigurationSectionHandler, Common.Logging”/>
</sectionGroup>
</configSections>
<common>
<logging>
<factoryAdapter type=”Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog”>
<arg key=”configType” value=”FILE” />
<arg key=”configFile” value=”~/NLog.config” />
</factoryAdapter>
</logging>
</common>
<appSettings>
<add key=”TimerInterval” value=”3000” />
<add key=”DateTimeFormat” value=”HH:mm:ss yyyy/MM/dd” />
</appSettings>
<startup>
<supportedRuntime version=”v4.0” sku=”.NETFramework,Version=v4.5” />
</startup>
<runtime>
<assemblyBinding xmlns=”urn:schemas-microsoft-com:asm.v1”>
<dependentAssembly>
<assemblyIdentity name=”NLog” publicKeyToken=”5120e14c03d0593c” culture=”neutral” />
<bindingRedirect oldVersion=”0.0.0.0-2.1.0.0” newVersion=”2.1.0.0” />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name=”Common.Logging” publicKeyToken=”af08829b84f0328e” culture=”neutral” />
<bindingRedirect oldVersion=”0.0.0.0-2.1.2.0” newVersion=”2.1.2.0” />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

記得要引用System.Configuration參考

啟動的時後取出參數傳入就行了