As you know, it is common practice to store connection strings in the app.config file. Plus, it's pretty simple.
However, if the application allows you to manage the list of connections (i.e., add a new connection, delete an existing one, edit an existing one), the changes in the connection strings will apply to all operating system users working with this application.
How to store connection strings for each user separately?
Tried to save in user.config. Connection strings are then saved and read fine, but if a user variable is stored in this file, then the next time this variable is read, an exception is thrown.
ConfigurationErrorsException: It is a mistake to use the section registered as allowExeDefinition = 'MachineToApplication' outside the application in the user configuration. (This is the default behavior unless otherwise noted)
The Internet is silent like a fish. Or I have an absolutely wrong approach to this issue?
//save connectionString in user.config ConnectionStringSettings cSS = new ConnectionStringSettings(NewConnName, NewConnString, _providerName); Configuration roaming = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal); ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = roaming.FilePath; Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); config.ConnectionStrings.ConnectionStrings.Add(cSS); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("connectionStrings"); Now user.config looks like this:
<?xml version="1.0" encoding="utf-8"?> <configuration> <connectionStrings> <add name="1" connectionString="Host=1;Port=1;Username=1;Database=1" providerName="Npgsql" /> </connectionStrings> <userSettings> <QConsole.Properties.Settings> <setting name="CurrentConnectionIndex" serializeAs="String"> <value>0</value> </setting> </QConsole.Properties.Settings> </userSettings> </configuration> If you try to read the variable the next time you start the application,
ComboBox_Connections.SelectedIndex = Properties.Settings.Default.CurrentConnectionIndex; then an exception is thrown