C# applicationSettings: how to update app.config?

后端 未结 4 971
滥情空心
滥情空心 2020-12-10 19:13

I am using .NET 4.0 and I would like to use the app.config file to store same parameter settings. I do the following. I use the Settings tab in the

4条回答
  •  爱一瞬间的悲伤
    2020-12-10 19:29

    Well, I read the link of Hari Gillala, in which one user suggested to edit directly the app.config file, that is a xml file.

    So in project properties-->settings I create the parameters that I need. Then, to load a parameter in code I do the following:

    _myViewModelProperty = MyApp.Properties.Settings.Default.MyParam1;
    

    In this way, I can read easily the information of the config parameter. Is typed, so in disign time I can see if the asign is correct or not.

    To update de config file, I edit the app.config file with the xml libraries of .NET.

        System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
        xml.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        System.Xml.XmlNode node;
        node = xml.SelectSingleNode("configuration/applicationSettings/MyApp.Properties.Settings/setting[@name='myparam1']");
        node.ChildNodes[0].InnerText = myNewValue;
        xml.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    

    In this way, I create a xml document (xml variable) and load the information of the app.config file. Then, I search for the node that I want to update, update its information (InnerText property) and finally I save the changes.

    In this way, I can update the app.config. It is what I want, because in a portable application, only one user will use it, and I want that the configuration is applied in any computer in which I run the application.

提交回复
热议问题