Jan 20, 2014
4 mins read
Windows Service可以透過幾種方式來傳入啟動參數 可以利用服務的啟動參數
還有一種方式是設定在服務機碼的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(); } }
}
最簡單好用的方式,莫過於透過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>
Sharing is caring!