Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationProperty is inaccessible due to its protection level

I wanna read/write (and save) application's configuration file in program

The app.config is like this:

<configuration>
  <configSections>
    <section name="AdWordsApi" type="System.Configuration.DictionarySectionHandler" requirePermission="false"/>
  </configSections>
  <AdWordsApi>
    <add key="LogPath" value=".\Logs\"/>
    ...
  </AdWordsApi>
</configuration>

When I use ConfigurationManager.GetSection to read the app.config, it works:

var adwords_section = (System.Collections.Hashtable) System.Configuration.ConfigurationManager.GetSection("AdWordsApi");
Console.WriteLine((string)adwords_section["LogPath"]);

But when I use ConfigurationManager.OpenExeConfiguration:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
ConfigurationSection section = config.GetSection("AdWordsApi");
Console.WriteLine(section["LogPath"]);

I always get this error:

'System.Configuration.ConfigurationElement.this[System.Configuration.ConfigurationProperty]' is inaccessible due to its protection level

But as I know, GetSection cannot save configuration at program runtime, Like I said at beginning: I wanna save configuration at program runtime, So I have to use OpenExeConfiguration.

I have googled for long time, what I found is to use AppSettings, but what I use is custom section..

Anyone could explain why this "ConfigurationProperty is inaccessible" error occured? Thanks

Edit:

I have set copy local of System and System.Configuration to true

like image 265
Mark Ma Avatar asked Dec 21 '11 09:12

Mark Ma


3 Answers

string key_value = refconfig.AppSettings.Settings["key_name"].Value;
like image 111
pcalkins Avatar answered Nov 04 '22 00:11

pcalkins


You can use this article.

Edit:

you can use config:

  <configSections>
    <section name="AdWordsApi.appSettings" type="System.Configuration.AppSettingsSection" />
  </configSections>
  <AdWordsApi.appSettings>
    <add key="LogPath" value=".\Logs\"/>
  </AdWordsApi.appSettings>

this code:

    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
    var settings = config.GetSection("AdWordsApi.appSettings") as AppSettingsSection;
    if (settings != null) Console.Write(settings.Settings["LogPath"].Value);
    Console.ReadLine();

Also You can use this article.

like image 44
sinanakyazici Avatar answered Nov 03 '22 23:11

sinanakyazici


I'm not sure if it will work for what you are trying to do, but have you tried using ConfigurationUserLevel.None instead?

like image 1
MEverett Avatar answered Nov 03 '22 22:11

MEverett