Question

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:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\dc2fa3d4\834ee436\assembly\dl3\cd068512) 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!

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top