try
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringSettings css = new ConnectionStringSettings("cString3", "abcdefxyz");
config.ConnectionStrings.ConnectionStrings.Add(css);
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
foreach (ConnectionStringSettings connection in connections)
{
string str = connection.Name;
string val = connection.ConnectionString;
MessageBox.Show(str + " " + val);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
So, I have implemented this on one of my projects (Enterprise Library 4.1):
private static void CopyCurrentDataConfiguration(IDataConfiguration dataConfig)
{
var configSource = ConfigurationSourceFactory.Create();
var dataConfigurationSection = (DatabaseSettings)configSource.GetSection(
DatabaseSettings.SectionName);
var defaultDatabaseName = dataConfigurationSection.DefaultDatabase;
CopyConnectionStrings(dataConfig, defaultDatabaseName);
}
private static void CopyConnectionStrings(IDataConfiguration dataConfig,string defaultDatabaseName)
{
foreach (ConnectionStringSettings settings in ConfigurationManager.ConnectionStrings)
{
try
{
var configuredDatabase = dataConfig
.ForDatabaseNamed(settings.Name)
.ThatIs
.AnotherDatabaseType(settings.ProviderName);
if (settings.Name.Equals(defaultDatabaseName))
{
configuredDatabase.AsDefault();
}
}
catch { }
}
}
public static void AddNewConnectionString(string databaseName, string connString)
{
var builder = new ConfigurationSourceBuilder();
var dataConfig = builder.ConfigureData();
CopyCurrentDataConfiguration(dataConfig);
dataConfig
.ForDatabaseNamed(databaseName)
.ThatIs
.AnotherDatabaseType("Oracle.DataAccess.Client")
.WithConnectionString(connString)
.AsDefault();
string conn = "your_connection_string";
var newConfigSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(newConfigSource);
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(newConfigSource);
}
Hope it helps.