Why does trying to load a System.Configuration.AppSettingsSection config section fail?

0

My App.Config (removing other stuff) looks like this:

<configuration>
  <configSections>
    <section name="Settings" type="System.Configuration.AppSettingsSection, System.Configuration" />
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>

  <connectionStrings>
    ...
  </connectionStrings>
  <appSettings>
    ...
  </appSettings>

  <Settings>
    <add key="something" value="5"/>
  </Settings>
</Configuration

I have a custom config section using System.Configuration.AppSettingsSection as key-value pairs is all I require. However when I try to access this with the following code:

var settings = (NameValueCollection)ConfigurationManager.GetSection("Settings");

I get an exception:

System.TypeInitializationException
  HResult=0x80131534
  Message=The type initializer threw an exception.
  Source=...
Inner Exception 1:
ConfigurationErrorsException: An error occurred creating the configuration section handler for Settings: Could not load file or assembly 'System.Configuration' or one of its dependencies. The system cannot find the file specified.

Inner Exception 2:
FileNotFoundException: Could not load file or assembly 'System.Configuration' or one of its dependencies. The system cannot find the file specified.

Why can it not utilise System.Configuration? I based this on code I saw online, so if there is a neater way to get the same effect I am happpy to change it - I just want to avoid writing a custom config-section class if I don't need to.

c#
.net
app-config
asked on Stack Overflow Jun 4, 2020 by Mr. Boy

1 Answer

0

As was alluded to in the comments, the issue was that System.Configuration.dll was not present in the execution folder.

I discovered that when adding a reference to a DLL/assembly in VS, the properties includes a "copy local" option which causes a copy to be copied as part of the build, rather than relying on the installed framework version.

This fixed my problem. I do not however understand why I needed to do this. It seems a bad idea to distribute a copy of a framework DLL. I'll leave my wnswer unaccepted for a time in case someone else can provide something more comprehensive explaining the why rather than just the how.

answered on Stack Overflow Jun 4, 2020 by Mr. Boy

User contributions licensed under CC BY-SA 3.0