Get Windows Service Name From App.Config In Installation

This blog describes how to fetch service name App.config at the time of installation.


Sometimes it is required to make the Windows service name configuration based. It means service name will fetch from App.config and install the service with the same name. In a simple way, it is not fetching the  correct value from App.config at the time of installation. Because the exe running Installer is InstallUtil.exe and ConfigurationManager will look for InstallUtil.exe.config, it provides the wrong result. Follow the below steps to achieve this. 


Step 1

Add following appSetting key in App.config to have service name.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <configuration>  
  3.   <startup>  
  4.     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1"/>  
  5.   </startup>  
  6.   <appSettings>  
  7.     <add key="ServiceName" value="ServiceMonitorV1"/>  
  8.   </appSettings>  
  9. </configuration>  
Next, right click on App.config and select properties. Change below two properties values,

Build Action -> None
Copy to Output Directory -> Copy Always

Follow below screen,


Step 2

Add method to fetch value from App.config. Below method fetches assembly information and its location.

Next it fetches the config directory based on assembly location. 
  1. public string GetServiceName()  
  2. {  
  3.     string serviceName = string.Empty;  
  5.     try  
  6.     {  
  7.         Assembly executingAssembly = Assembly.GetAssembly(typeof(ProjectInstaller));  
  8.         string targetDir = executingAssembly.Location;  
  9.         Configuration config = ConfigurationManager.OpenExeConfiguration(targetDir);  
  10.         serviceName = config.AppSettings.Settings["ServiceName"].Value.ToString();  
  12.         return serviceName;  
  13.     }  
  14.     catch (Exception ex)  
  15.     {  
  16.         return "MyWinService";  
  17.     }  
  18. }  
Step 3

Call above method in ProjectInstaller.Designer.cs and ProjectInstaller.cs
  1. // ProjectInstaller.Designer.cs  
  2. this.serviceInstaller1.ServiceName = new CommonUtil().GetServiceName();  
  4. // ProjectInstaller.cs  
  5. private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)  
  6. {  
  7.     ServiceController sc = new ServiceController(new CommonUtil().GetServiceName());  
  8.     sc.Start();  
  9. }  
In this blog we discussed how to get Service name from App.config file at the time of installation. Hope it helps.