ConfigurationManager.ConnectionStrings.Add

My mind is stunned here. There is an Add method on ConfigurationManager.ConnectionStrings However, if I use it, it throws a read-only error message. My research on the problem showed that we cannot add connection strings programmatically at runtime in app.config. A traversal is used for this, using reflection to set the ReadOnly flag to false.

Here is an example with reflection:

public static void AddConnectionString(SqlConnectionStringBuilder connectionString,string Name) { try { typeof(ConfigurationElementCollection).GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ConfigurationManager.ConnectionStrings, false); ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings(Name, connectionString.ConnectionString)); EventLogger.LogEvent("Added ConnectionString",1); ProtectConnectionStrings(); } catch (Exception ex) { EventLogger.LogError(ex.Message,(int)EventLogger.Events.GeneralException); } } 

But none of this makes sense to me. I want to save conStrs in app.config so that I can encrypt them. I need users to be able to add them to app.config at runtime. What is the standard way to accomplish this?

+4
source share
1 answer

The app.config file should not be edited by the application. One way to say that the point is to think about where it is located next to the executable file in a folder that (by default) cannot be written by the user or user applications (program files).

I would say that if this is what the user modifies, it should be stored in the settings.

In addition, you can create custom configuration files and use the same System.Configuration material to access it. But this is a little cumbersome, and I'm not sure what you will get from it using the usual settings files.

+1
source

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


All Articles