If you compile a project as a library, then it reads from the app.config of the calling executable. If you compile a project as an executable, then it reads from it's own app.config.
Custom MSBuild Task not reading from App.config [C#]
-
31-05-2022 - |
Question
I wrote a custom build task that reads values form the appsettings in it's App.config file. When I compile my task as an executable and run it, the task works perfectly. The correct values are read from the config file. However when I compile it as an assembly and run it from a target in my build script I get a System.NullReferenceException. The exception occurs in the foreach loop because the configuration manager returns null.
IEnumerable<string> tables = ConfigurationManager.AppSettings.GetValues(key);
foreach (string txt in tables)
{
Logic.....
}
I'm calling the custom task correctly because I commented out the issue and it builds successfully.
Does anyone know why this might be happening? or if I'm even able to use a App.config file with custom build tasks?
Thanks in advance
Solution
OTHER TIPS
If anyone is interested I used the following code to access the custom config
private static string[] GetConfigFile()
{
var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = @"C:\ConfigFile.config";
config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
return config.AppSettings.Settings.AllKeys;
}
The above code gets the list of keys from the specified config file. The return value is stored in a string array which I run through using a foreach loop as seen below
string[] keyNames = GetConfigFile();
foreach (string keys in keyNames )
{
KeyValueConfigurationElement keyval = config.AppSettings.Settings[keys];
Console.WriteLine(keyval.Value);
}