C# applicationSettings:如何更新 app.config?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13286916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:04:34  来源:igfitidea点击:

C# applicationSettings: how to update app.config?

c#app-config

提问by álvaro García

I am using .NET 4.0 and I would like to use the app.configfile to store same parameter settings. I do the following. I use the Settingstab in the project properties to create my parameters.

我正在使用 .NET 4.0 并且我想使用该app.config文件来存储相同的参数设置。我执行以下操作。我使用Settings项目属性中的选项卡来创建我的参数。

This add the information in the app.configfile like this:

这将在app.config文件中添加信息,如下所示:

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

But this causes an error, that param1is read-only.

但这会导致错误,即param1只读。

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

那么如何从我的代码更新我的配置文件呢?

采纳答案by álvaro García

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.

好吧,我读了 Hari Gillala 的链接,其中一位用户建议直接编辑 app.config 文件,即一个 xml 文件。

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.

这样我就可以很容易的读取到config参数的信息了。是打字的,所以在设计时我可以查看分配是否正确。

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

为了更新配置文件,我使用 .NET 的 xml 库编辑 app.config 文件。

    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.

这样我就创建了一个xml文档(xml变量),并加载了app.config文件的信息。然后,我搜索要更新的节点,更新其信息(InnerText 属性),最后保存更改。

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.

这样我就可以更新app.config了。这正是我想要的,因为在便携式应用程序中,只有一个用户会使用它,而且我希望该配置适用于我运行该应用程序的任何计算机。

回答by bitsmuggler

Mark your setting as usersetting.

将您的设置标记为用户设置。

Detailed article: http://www.codeproject.com/Articles/25829/User-Settings-Applied

详细文章:http: //www.codeproject.com/Articles/25829/User-Settings-Applied

回答by il_guru

You should use Properties.Settingsto perform this action. You can look at this documentationfor more information.

您应该使用Properties.Settings来执行此操作。您可以查看此文档以获取更多信息。

//modify
Properties.Settings.Default.param1 = false;
//save the setting
Properties.Settings.Default.Save();

Note that if your settings have the Scope of User, which they must be to be writeable, then the properties are saved somewhere else and not in your local config file. See herefor the details.

请注意,如果您的设置具有用户范围,它们必须是可写的,那么这些属性将保存在其他地方,而不是保存在您的本地配置文件中。详情请见此处

EDIT after discussion in comment and further searches:

在评论和进一步搜索中讨论后编辑:

My suggestion to achieve the desired result would be to switch to AppSettings. That is because, after some searches, i found out that appsettings changes the .config file in the Application Data folder (running some tests on my machine confirm that).

我建议实现预期结果是切换到AppSettings。这是因为,经过一些搜索,我发现 appsettings 更改了 Application Data 文件夹中的 .config 文件(在我的机器上运行一些测试确认了这一点)。

Look at comment in the answer to this question.

看看这个问题的答案中的评论。

I am not sure if there is some work around, but if you want your application to have a portable app.config file, i think the only way is to switch to AppSettingswhich i'm sure can save changes in the app.config found in the program folder.

我不确定是否有一些解决方法,但是如果您希望您的应用程序具有可移植的 app.config 文件,我认为唯一的方法是切换到AppSettings,我确信可以保存找到的 app.config 中的更改在程序文件夹中。

EDIT 2: Possible solution

编辑 2:可能的解决方案

I found out a possible solution to make your app portable! You can change the Provider used by Settings to save the application's settings creating a custom Provider.

我找到了一个可能的解决方案,使您的应用程序可移植!您可以更改 Settings 使用的 Provider 以保存应用程序的设置,从而创建自定义 Provider。

The answer to this questionprovide a link to a code to make applicationsettings portable. I think you give it a try

这个问题的答案提供了一个代码链接,使应用程序设置可移植。我想你试一试

回答by Manny

Here's my function to update or add an entry into the app.config for "applicationSettings" section. There might be a better way, but this works for me. If anyone can suggest a better method please share it, we'll always looking for something better.

这是我在 app.config 中为“applicationSettings”部分更新或添加条目的功能。可能有更好的方法,但这对我有用。如果有人可以提出更好的方法,请分享它,我们将一直在寻找更好的方法。

    static string APPNODE = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Properties.Settings";
    static DateTime now = DateTime.Now;
    Utilities.UpdateConfig(APPNODE, "lastQueryTime", now.ToString());

    static public void UpdateConfig(string section, string key, string value)
    {
        Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        ClientSettingsSection applicationSettingsSection = (ClientSettingsSection)config.SectionGroups["applicationSettings"].Sections[section];
        SettingElement element = applicationSettingsSection.Settings.Get(key);

        if (null != element)
        {
            applicationSettingsSection.Settings.Remove(element);
            element.Value.ValueXml.InnerXml = value;
            applicationSettingsSection.Settings.Add(element);
        }
        else
        {
            element = new SettingElement(key, SettingsSerializeAs.String);
            element.Value = new SettingValueElement();
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            element.Value.ValueXml = doc.CreateElement("value");

            element.Value.ValueXml.InnerXml = value;
            applicationSettingsSection.Settings.Add(element);
        }

        config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("applicationSettings");            
    }