Updating .config file from an Custom Installer Class Action

后端 未结 5 1267
春和景丽
春和景丽 2021-02-04 20:03

I\'ve tried updating my application\'s .config file during installer (via a .NET Installer Class Action). But, I can\'t seem to get ConfigurationManager to lis

5条回答
  •  南方客
    南方客 (楼主)
    2021-02-04 20:40

    You can access these settings using the System.Configuration namespace but, its not as simple as I would like and in retrospect using System.Xml.Linq is far simpler. Anyway, here is how I got it to work.

    The important concept is, the applicationSettings section is not AppSettings, its a seperate section supported by the ClientSettingsSection type.

    //Open the application level config file
    ExeConfigurationFileMap exeMap = new ExeConfigurationFileMap();
    exeMap.ExeConfigFilename = String.Format("{0}.config", 
        Context.Parameters["assemblypath"]);
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap,
        ConfigurationUserLevel.None);
    
    //Get the settings section
    ClientSettingsSection settingsSection =
        config.GetSectionGroup("applicationSettings").Sections
             .OfType().Single();
    
    //Update "TheSetting"
    //I couldn't get the changes to persist unless
    //I removed then readded the element.
    
    SettingElement oldElement = settingsSection.Get("TheSetting");
    settingsSection.Settings.Remove(oldElement);
    
    SettingElement newElement = new SettingElement("TheSetting", 
        SettingSerializeAs.String);
    newElement.Value = new SettingValueElement();
    newElement.Value.ValueXml = oldElement.Value.ValueXml.CloneNode(true);
    newElement.Value.ValueXml.InnerText = "Some New Value";
    settingsSection.Add(newElement);
    
    //Save the changes
    config.Save(ConfigurationSaveMode.Full);
    

    So, as you can see, simple. :-S

提交回复
热议问题