none
Editing Configuration Files From Code

    Question

  • How can I make dynamic edits to my application's Configuraiton files stick after program execution completes?  The updates from the console application below (VS2008) work (i.e. update the file with .config extension in my \bin\Debug directory) while I'm stopped in debug mode, but once program execution completes, the config file reverts back to its prior state.

     

    Here's my sample config file settings and code:

     

    <?xml version="1.0" encoding="utf-8" ?>

    <configuration>

    <configSections>

    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

    <section name="DiagnosticsAndInstrumentation.TestSection" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />

    </sectionGroup>

    </configSections>

    <userSettings>

    <DiagnosticsAndInstrumentation.TestSection>

    <setting name="TestString1" serializeAs="String">

    <value>aaa</value>

    </setting>

    <setting name="TestString2" serializeAs="String">

    <value>bbb</value>

    </setting>

    </DiagnosticsAndInstrumentation.TestSection>

    </userSettings>

    </configuration>

     

    using System;

    using System.Configuration;

    using System.Text;

    using System.Xml;

    namespace DiagnosticsAndInstrumentation

    {

    class Program

    {

    static void Main(string[] args)

    {

    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    ClientSettingsSection userSettingsSection = (ClientSettingsSection)configuration.SectionGroups["userSettings"].Sections["DiagnosticsAndInstrumentation.TestSection"];

    // Try to delete an element using ClientSettingsSection and SettingElement classes

    SettingElement elemToDelete = null;

    foreach (SettingElement connStr in userSettingsSection.Settings)

    {

    if (connStr.Name == "TestString1")

    {

    elemToDelete = connStr;

    break;

    }

    }

    if (elemToDelete != null)

    {

    userSettingsSection.Settings.Remove(elemToDelete);

    }

    // Try to add an element using SettingElement

    XmlDocument doc = new XmlDocument();

    SettingElement element = new SettingElement("TestString5", SettingsSerializeAs.String);

    SettingValueElement value = new SettingValueElement();

    XmlNode newNode2 = doc.CreateNode(XmlNodeType.Element, "Value", "");

    newNode2.InnerText = "ddd";

    value.ValueXml = newNode2;

    element.Value = value;

    userSettingsSection.Settings.Add(element);

    userSettingsSection.SectionInformation.ForceSave = true;

    configuration.Save(ConfigurationSaveMode.Full);

    }

    }

    }

    Monday, March 03, 2008 3:07 AM

Answers

  • Hello,

     

    Which config file changed when you stopped in debug mode? Is it ConsoleApplication.vshost.exe.Config file?

     

    If true, I believe you are debugging in VS HOSTING Process which is a new feature in VS 2005.

    For more information about it: http://blogs.msdn.com/dtemp/archive/2004/08/17/215764.aspx

     

    I suggest you can disable it by 1) Right-Click on your project and select “Properties”, 2) In Debug page, uncheck the box before “Enable the visual studio hosting process”.

     

    Hope this helps.

    Best regards,

    Wen Yuan

    Tuesday, March 04, 2008 11:12 AM

All replies

  • do it like this:

    Code Snippet




    try
                {
                    reader.WhitespaceHandling = WhitespaceHandling.None;
                    XmlDocument xmlDoc = new XmlDocument();
                    //Load the file into the XmlDocument
                    xmlDoc.Load(reader);
                    // Have the routine which is doing the chenge values for attributes here
                    reader.Close();
                    xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "\\AppConfig.xml");
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    //Close off the connection to the file.
                    reader.Close();
                }


    this will certainly save the data.

    Monday, March 03, 2008 5:08 PM
  • I attempted what you describe above (though it will be a shame if all the Configuration namespace classes cannot be used), but I still get the same behavior - changes happen while the code is running, but once program execution completes, config file reverts back to prior state.  I also tried compiling and running in Release mode, but Config file is not affected there either.  Here are the modified contents of my Main() function:

     

    XmlReader reader = XmlReader.Create(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

    XmlDocument doc = new XmlDocument();

    doc.Load(reader);

    XmlNodeList testSecnNodes = doc.GetElementsByTagName("DiagnosticsAndInstrumentation.TestSection");

    XmlNode testSecnNode = testSecnNodes[0];

    XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "setting", null);

    XmlAttribute nameAttribute = doc.CreateAttribute("name");

    nameAttribute.Value = "TestString6";

    XmlAttribute serializeAsAttribute = doc.CreateAttribute("serializeAs");

    serializeAsAttribute.Value = "String";

    XmlNode newNodeValue = doc.CreateNode(XmlNodeType.Element, "value", null);

    newNodeValue.InnerText = "ppp";

    newNode.Attributes.Append(nameAttribute);

    newNode.Attributes.Append(serializeAsAttribute);

    newNode.AppendChild(newNodeValue);

    testSecnNode.AppendChild(newNode);

    reader.Close();

    doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

     

    Any thoughts? 

     

    Thanks!

    Tuesday, March 04, 2008 3:57 AM
  • Hello,

     

    Which config file changed when you stopped in debug mode? Is it ConsoleApplication.vshost.exe.Config file?

     

    If true, I believe you are debugging in VS HOSTING Process which is a new feature in VS 2005.

    For more information about it: http://blogs.msdn.com/dtemp/archive/2004/08/17/215764.aspx

     

    I suggest you can disable it by 1) Right-Click on your project and select “Properties”, 2) In Debug page, uncheck the box before “Enable the visual studio hosting process”.

     

    Hope this helps.

    Best regards,

    Wen Yuan

    Tuesday, March 04, 2008 11:12 AM
  • Thank you!  That was it.  But why would the VS Hosting Process prevent changes to its configuration file from persisting? 

     

    Tuesday, March 04, 2008 9:10 PM
  • Hello,

     

    The hosting process is a feature in Visual Studio 2005 that improves debugging performance, enables partial trust debugging, and enables design time expression evaluation. Visual Studio virtually hosts the application and as a result utilizes some temporary host files. The change in temporary host files won't take effect. Hosting process files are for use by Visual Studio 2005 and should not be run directly or deployed with your application. This behavior is designed. I think you can get benefit when testing. Because you can test your application again and again without backuping config file...

     

    Hope this helps.

    Best regards,

    Wen Yuan

    Thursday, March 06, 2008 2:44 AM
  • Thank you again for your help, and for the explanation - I see your point about rerunnability.
    Thursday, March 06, 2008 3:32 AM
  • Hi,

    As suggested by Wen Yuan Wang, I turned off the the Visual Studio hosting process and verified that the changes are saved to MyApp.exe.config file instead of MyApp.vhost.exe.config file when still running under Debug configuration. However when I deployed my application with Release configuration to C:\UAT\MyApp\, it would not save the changes to C:\UAT\MyApp\Application Files\MyAPP_1_0_0_0\MyApp.exe.config file. I checked file permissions and made sure that ReadOnly is not checked for MyApp.exe.config file.

    In addition, I also tried to SaveAs(persist\MyApp_yyyymmdd.config). While running in Debug mode inside Visual Studio 2008 (vhosting turned off), it does create 'persist' folder under bin/Debug and saves the file there. However the deployed version in C:\UAT\MyApp\ does not create such folder. I made sure all folders under C:\UAT are not set to ReadOnly.

    I am using Visual Studio 2008. Appreciate any help on this.

    Regards
    Amit

    Monday, October 05, 2009 4:32 AM