如何动态加载单独的应用程序设置文件并与当前设置合并?

时间:2010-03-05 19:15:14

标签: .net persistence configuration-files settings

有关于reading settings from a separate config file和其他类似问题的问题,但我的问题是针对应用程序属性设置(即<MyApplication.Properties.Settings> - 请参阅下面的XML文件)以及如何动态加载它们。我尝试了this post中的方法,其中涉及刷新主配置文件的整个appSettings部分,但我的改编引发了异常,因为我没有替换appSettings部分:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
// Have tried the other ConfigurationUserLevels to no avail
config.AppSettings.File = myRuntimeConfigFilePath;
config.Save(ConfigurationSaveMode.Modified); // throws ConfigurationErrorsException
ConfigurationManager.RefreshSection("userSettings");

ConfigurationErrorsException.Message是“根元素必须与引用文件的部分的名称匹配'appSettings'(C:\ myFile.xml第2行)。”该文件是:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <MyApplication.Properties.Settings>
            <setting name="SineWaveFrequency" serializeAs="String">
                <value>6</value>
            </setting>
            <setting name="SineWaveAmplitude" serializeAs="String">
                <value>6</value>
            </setting>
        </MyApplication.Properties.Settings>
    </userSettings>
</configuration>

有没有办法将此文件中的值导入MyApplication.Properties.Settings.Default类,框架处理所有XML反序列化,就像在应用程序启动时加载配置文件一样?

2 个答案:

答案 0 :(得分:7)

嗯,这很有效:

using System;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

public static class SettingsIO
{
    internal static void Import(string settingsFilePath)
    {
        if (!File.Exists(settingsFilePath))
        {
            throw new FileNotFoundException();
        }

        var appSettings = Properties.Settings.Default;
        try
        {
            var config = 
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);

            string appSettingsXmlName = 
Properties.Settings.Default.Context["GroupName"].ToString(); 
// returns "MyApplication.Properties.Settings";

            // Open settings file as XML
            var import = XDocument.Load(settingsFilePath);
            // Get the whole XML inside the settings node
            var settings = import.XPathSelectElements("//" + appSettingsXmlName);

            config.GetSectionGroup("userSettings")
                .Sections[appSettingsXmlName]
                .SectionInformation
                .SetRawXml(settings.Single().ToString());
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("userSettings");

            appSettings.Reload();
        }
        catch (Exception) // Should make this more specific
        {
            // Could not import settings.
            appSettings.Reload(); // from last set saved, not defaults
        }
    }

    internal static void Export(string settingsFilePath)
    {
        Properties.Settings.Default.Save();
        var config = 
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.PerUserRoamingAndLocal);
        config.SaveAs(settingsFilePath);
    }
}

导出方法创建如下文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <userSettings>
        <MyApplication.Properties.Settings>
            <setting name="SineWaveFrequency" serializeAs="String">
                <value>1</value>
            </setting>
            <setting name="SineWaveAmplitude" serializeAs="String">
                <value>100</value>
            </setting>
            <setting name="AdcShift" serializeAs="String">
                <value>8</value>
            </setting>
            <setting name="ControlBitsCheckedIndices" serializeAs="String">
                <value>0,1,2,3,5,6,7,8</value>
            </setting>
            <setting name="UpgradeSettings" serializeAs="String">
                <value>False</value>
            </setting>
        </MyApplication.Properties.Settings>
    </userSettings>
</configuration>

import方法解析该文件,获取节点内的所有内容,将该XML放入相应部分的user.config文件中,然后重新加载Properties.Settings.Default以便从新用户获取这些值。配置文件。

答案 1 :(得分:0)

Pat提出的解决方案:

// Get the whole XML inside the settings node
var settings = import.XPathSelectElements("//" + appSettingsXmlName);

返回null。我把它改成了

var settings = import.Element("configuration").Element("userSettings").Element(appSettingsXmlName);

config.GetSectionGroup("userSettings")
      .Sections[appSettingsXmlName]
      .SectionInformation
      .SetRawXml(settings.ToString());

它完美无缺。