Today I noticed how non-intuitive it is to write to the configuration file programatically for an application. What I needed to do was dynamically create a connection string, then write it to the app.config file.
Here’s how you do it:
first, you need to add a project reference to the System.Configuration assembly. Add a corresponding using clause to the top of your class.
Next you need to find and open the configuration file. In win forms, you do this by specifying the full path to your application’s executable. If you project is at c:\code\project1 then you would pass in something like this: “c:\code\project1\bin\debug\project1.exe”.
Configuration config = ConfigurationManager.OpenExeConfiguration(FULL_EXE_PATH);
ConnectionStringSettings connStringSettings = new ConnectionStringSettings("database",
"connection_string_here");
config.ConnectionStrings.ConnectionStrings.Add(connStringSettings);
config.Save();
For ASP.NET, you can follow the same principle, but use the System.Web.Configuration namespace in conjunction with WebConfigurationManager.OpenWebConfiguration(path) where path is the url of your root, for example http://localhost/webapp1 (notice there is no trailing slash).
I'm Ben Scheirman. I am a .NET software developer with a strong interest in agility. I work as a Principal Consultant with Sogeti.
Read more here.
email me
Ads by The Lounge
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.