.NET Installer cannot access your App.config

I’ve been caught by this once before and so it’s time to ensure it’s documented.

I’ve created an Installer for a Windows Service in .NET, it’s a fairly generic service (or more succinctly it’s an application that allows me to create services with minimal code) so I want it to be easy to give it a service name that properly represents it’s functionality (not the generic container’s name). So I added an appSettings section to the App.config and tried to install the service using InstallUtil and ofcourse it failed to get the info. from the App.Config.

Whilst the code for the Installer is within the EXE assembly, it’s run via InstallUtil so cannot pick up the correct App.config automatically. It’s simple to implement this functionality, see the code below

string configFile = Assembly.GetExecutingAssembly().Location + ".config";

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configFile;

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map,   
                              ConfigurationUserLevel.None);
	
string serviceName = config.AppSettings.Settings["ServiceName"].Value;
serviceInstaller.ServiceName = serviceName ?? DEFAULT_SERVICE_NAME;

In the sample above I have a fallback DEFAULT_SERVICE_NAME in case we forget to set the config as follows

<appSettings>
  <add key="ServiceName" value="My Application"/>
</appSettings>