Should I be retrieved from ConfigurationSection to support settings for each user?

I play with .NET configuration support (ConfigurationManager class and related support classes). I would like to write an application that after installation:

  • It has default settings in the file foo.exe.config (in Program Files).
  • The user can later override the parameters with invalid values ​​that must be saved.
  • User preferences should be stored in the user profile, as he should not have write access to the Program Files directory.

The application should use the user settings when they are installed, otherwise use the default values.

It seems that it should be easy - this is a very common picture. But my attempts in this were confused, and I wonder if I make the right decision.

The following code throws an exception at runtime. "ConfigurationSection properties cannot be edited when locked."

using System;
using System.Configuration;

namespace DemoAppSettingsProblem
{
    class Program
    {
        static void Main(string[] args)
        {
            Configuration userConfig =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            if ( userConfig.AppSettings.Settings["foo"] != null )
                userConfig.AppSettings.Settings.Remove("foo");

            userConfig.AppSettings.Settings.Add("foo", "The string is foo.");

            userConfig.Save(ConfigurationSaveMode.Modified);    // exception!
        }
    }
}

The problem is that the .NET-defined section is <appSettings>declared by default allowExeDefinition=MachineToApplication(see this nice post by Microsoft Irena Kennedy). This prevents the section from being written to the user profile (local or roaming).

, , , allowExeDefinition=MachineToLocalUser. , MSDN, , , ConfigurationSection. , , , - .

? , .NET , , , ?

+3
2

, .NET 2.0 , ""? app.config - <applicationSettings>, <userSettings> , , , allowExeDefinition=MachineToLocalUser, .

, ? , , ( "mySettings" ).

+1

Source: https://habr.com/ru/post/1707803/


All Articles