Can I Add ConnectionStrings to the ConnectionStringCollection at Runtime?

前端 未结 8 1421
心在旅途
心在旅途 2020-12-15 18:38

Is there a way where I can add a connection string to the ConnectionStringCollection returned by the ConfigurationManager at runtime in an Asp.Net application?

I hav

8条回答
  •  囚心锁ツ
    2020-12-15 18:52

    You can use reflection to disable the private bReadOnly field (bad idea, etc.):

    typeof(ConfigurationElementCollection)
        .GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic)
        .SetValue(ConfigurationManager.ConnectionStrings, false);
    ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings());
    

    This is similar to the technique required to modify an existing connection string, and added as a comment there by Brian Rodgers.

提交回复
热议问题