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?
source share