Monday, April 13, 2009

Updating .config Files from Visual Studio Setup Project

To open Web.config from within a web setup project:

string path = Context.Parameters["assemblypath"];
path = path.Substring(0, path.LastIndexOf(
           Path.DirectorySeparatorChar));
path = Path.Combine(path, "Web.config");
var config = 
    ConfigurationManager.OpenExeConfiguration(path)

To open App.config from within a setup project:

var map = new ExeConfigurationFileMap();
map.ExeConfigFilename = 
    Context.Parameters["assemblypath"] + ".config";
var config = 
    ConfigurationManager.OpenMappedExeConfiguration(
        map, ConfigurationUserLevel.None);

To update settings in .config files

// update connection strings
var cs = config.ConnectionStrings;
cs.ConnectionStrings["cs1"].ConnectionString = 
    BuildConnectionString(host, user, pass);

// update app settings
var appSettings = config.AppSettings;
appSettings.Settings["key"].Value = "new value";   

Finally, to save the .config file changes

config.Save();

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.