NEWS

Wednesday, December 28, 2011

Editing web.config in asp.net



 There are multiple ways you can go about actually doing the editing of this file, however you have to make sure that the account you are running your application under has the appropriate file system permissions to be able to write to the application directory (eg edit and save the web.config file). If you are in a clustered environment, I would strongly advise not going down this path (though still possible).
Once your permissions etc have been sorted out, below is a quick way of doing it.
public void EditMyWebConfig(string appSettingsKey, string appSettingsValue, string         filePath)
    {
        XmlDocument xml = new XmlDocument();
        //Load current config into memory
        xml.Load(filePath);
        //Overwrite config
        using(FileStream fs = new FileStream(filePath, FileMode.Create,FileAccess.ReadWrite))
        {
            //select appSetting you want to edit
            XmlNode xmlN = xml.SelectSingleNode("//configuration/appSettings/add[@key = '" + appSettingsKey + "']");
            //assign new value
            xmlN.Attributes["value"].Value = appSettingsValue;
            //Create new web config
            xml.Save(fs);
        }
    }
Another way is:

System.Configuration.Configuration conf = WebConfigurationManager.OpenWebConfiguration(Server.MapPath);
conf.AppSettings.Settings["SessioneTimeout"].Value = "30";
conf.Save();

4 comments: