I have an Web.Api application that uses functions from a different assembly. For this assembly I have created a .config file where I store some strings.
I am using the following code which should fetch one of those strings:
private static string LogUrl = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings.Settings["WebApi-LogUrl"].Value.ToString();
Assembly.GetExecutingAssembly().Location points to temporary asp.net files, (C:WindowsMicrosoft.NETFramework64v4.0.30319Temporary ASP.NET Filesrootdc2fa3d4834ee436assemblydl3cd068512) but my dll.config file is not copied there.
The result is that I cant debug my application and it also gives null when running the code on a real IIS server.
If I set a break point just before getting the setting I can get hold of the temporary folder, and when I copy my dll.config file there it all works, but how should I make do that automatically.
I have the properties for my dll.config file set as “Build action: content”, “Copy to output directory: always”
Any help would be appreciated, have googled for hours now. 🙁
Best regards,
Peter Larsson!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
I solved this by using the following code:
// The dllPath can't just use Assembly.GetExecutingAssembly().Location as ASP.NET doesn't copy the config to shadow copy path
var dllPath = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath;
var dllConfig = ConfigurationManager.OpenExeConfiguration(dllPath);
// Get the appSettings section
var appSettings = (AppSettingsSection) dllConfig.GetSection("appSettings");
return appSettings.Settings;
The key there is:
new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath
I came up with that solution after reading Zhaph – Ben Duguid‘s answer here: https://stackoverflow.com/a/2434339/103778.
Now I’m able to pick up my DLL’s configuration file that is in the bin directory of my web app.
I have since written up a blog post discussing this further.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0