C#的applicationSettings:如何更新的app.config? [英] C# applicationSettings: how to update app.config?

查看:1088
本文介绍了C#的applicationSettings:如何更新的app.config?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用.NET 4.0,我想使用的app.config 文件来存储相同的参数设置。我这样做。我用的是设置标签中的项目属性创建我的参数。

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 project properties to create my parameters.

这增加了信息的的app.config 文件是这样的:

This add the information in the app.config file like this:

<MyApp.Properties.Settings>
      <setting name="param1" serializeAs="String">
        <value>True</value>
      </setting>
<MyApp.Properties.Settings>

在我的视图模型(在我的代码),我可以接触到这样的信息:

In my view model (in my code) I can access to the information in this way:

bool myBool = MyApp.Properties.Default.param1;

当我试图改变在配置文件中的值,我试试这个:

When I try to change the value in the config file, I try this:

Properties.Settings.Default.param1 = false;



但是,这将导致一个错误,即参数1 是只读的。

那么,怎样才能从我的代码更新我的配置文件?

So how can I update my config file from my code?

推荐答案

好吧,我读哈日Gillala的链接,其中一个用户建议直接编辑app.config文件,这是一个XML文件。

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;

在这种方式,我可以很容易地读取配置参数的信息。被输入,所以在disign时候,我可以看到,如果ASIGN的正确与否。

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.

要更新去配置文件,我编辑的XML库app.config文件。.NET程序

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);

在这种方式中,我创建一个XML文档(XML变量)和加载应用程序的信息。配置文件。然后,我搜索,我要更新,更新其信息(InnerText属性),最后我保存更改的节点。

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.

在这种方式,我可以更新app.config中。这是我想要的,因为在便携式应用中,只有一个用户会使用它,我想,该配置是在我运行应用程序的任何计算机应用。

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.

这篇关于C#的applicationSettings:如何更新的app.config?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆