Sunday, March 27, 2011

change connection string & reload app.config at run time

when i change connection string through this code it not reload app.config at runtime how we reload app config

config.ConnectionStrings.ConnectionStrings["JVVNL_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString;
config.ConnectionStrings.ConnectionStrings["CMS_NEW.Properties.Settings.JVVNL_NEWConnectionString1"].ConnectionString = ConString;

config.Save(ConfigurationSaveMode.Modified,true);
ConfigurationManager.RefreshSection(config.ConnectionStrings.SectionInformation.SectionName);
From stackoverflow
  • IIRC, the ConfigurationManager.RefreshSection requires a string parameter specifying the name of the Section to refresh :

    ConfigurationManager.RefreshSection("connectionStrings");
    

    I think that the ASP.NET application should automatically reload when the ConnectionStrings element is modified and the configuration does not need to be manually reloaded.

  • Yeah, when ASP.NET web.config gets updated, the whole application gets restarted which means the web.config gets reloaded.

  • You can also refresh the configuration in it's entirety:

    ConnectionStringSettings importToConnectionString = currentConfiguration.ConnectionStrings.ConnectionStrings[newName];
    
    if (importToConnectionString == null)
    {
        importToConnectionString = new ConnectionStringSettings();
        importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
        importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
        importToConnectionString.Name = newName;
        currentConfiguration.ConnectionStrings.ConnectionStrings.Add(importToConnectionString);
    }
    else
    {
        importToConnectionString.ConnectionString = importFromConnectionString.ConnectionString;
        importToConnectionString.ProviderName = importFromConnectionString.ProviderName;
    }
    
    Properties.Settings.Default.Reload();
    
    robnardo : Hi Neil, could you maybe expand on your answer? I am a noob. How do I set currentConfiguration and importFromConnectionString ?

0 comments:

Post a Comment