Music. Coding. Gaming. Life.

Changing app.config on the fly

Posted Friday, July 20th, 2007 6:35:00 pm
After banging my head against the wall several times trying to insert a dynamic ConnectionString into my app.config, I figured it out. It's nowhere near obvious, though. Import System.Configuration to get it functional. Here's an example of how to modify the connectionStrings section.

' Load configuration
Dim cfgConfig As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

' Gotta try to remove it first, if it exists you'll crash out.
Try
    cfgConfig.ConnectionStrings.ConnectionStrings.Remove("conn")
Catch ex As Exception
End Try

' Add new connection
cfgConfig.ConnectionStrings.ConnectionStrings.Add(new ConnectionString("conn", strConnString, strProvider)

' Save the file
cfgConfig.Save()

' Force the application to refresh this section from the file at runtime.
ConfigurationManager.RefreshSection("connectionStrings")

Comments

Loading...
roncli.com Media Player