读写值in.NET .config文件(Reading and writing values in.

2019-09-17 01:00发布

我想用一个自定义路径的user.config文件,而不是让.NET从默认位置读取它。

我打开这样的文件:

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = String.Format("{0}\\user.config",AppDataPath);
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.PerUserRoamingAndLocal);

但我无法弄清楚如何真正读出它的设置,我得到一个编译错误,指出该值是不可访问,当我试图通过应用程序数据或配置节得到的值。

我需要建立某种形式的包装类的正常消耗的数据?

Answer 1:

我最近有一个类似的问题负责,我不得不改变的地方设置文件被从应用程序数据的应用程序目录的默认位置读取的位置。 我的解决方案是创建一个源自我自己的设置文件ApplicationSettingsBase其指定的自定义SettingsProvider 。 虽然该解决方案感觉就像矫枉过正起初,我发现它变得更加灵活和可维护,比我的预期。

更新:

样品设置文件:

public class BaseSettings : ApplicationSettingsBase
{
    protected BaseSettings(string settingsKey)
       { SettingsKey = settingsKey.ToLower(); }


    public override void Upgrade()
    {
         if (!UpgradeRequired)
             return;
         base.Upgrade();
         UpgradeRequired = false;
         Save();
    }


    [SettingsProvider(typeof(MySettingsProvider)), UserScopedSetting]
    [DefaultSettingValue("True")]
    public bool UpgradeRequired
    {
         get { return (bool)this["UpgradeRequired"]; }
         set { this["UpgradeRequired"] = value; }
    }
}

样品SettingsProvider:

public sealed class MySettingsProvider : SettingsProvider
{
    public override string ApplicationName { get { return Application.ProductName; } set { } }
    public override string Name { get { return "MySettingsProvider"; } }


    public override void Initialize(string name, NameValueCollection col)
         { base.Initialize(ApplicationName, col); }


    public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection propertyValues)
    {
       // Use an XmlWriter to write settings to file. Iterate PropertyValueCollection and use the SerializedValue member
    }


    public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection props)
    {
       // Read values from settings file into a PropertyValuesCollection and return it
    }


    static MySettingsProvider()
    {
        appSettingsPath_ = Path.Combine(new FileInfo(Application.ExecutablePath).DirectoryName, settingsFileName_);

        settingsXml_ = new XmlDocument();
        try { settingsXml_.Load(appSettingsPath_); }
        catch (XmlException) { CreateXmlFile_(settingsXml_); } //Invalid settings file
        catch (FileNotFoundException) { CreateXmlFile_(settingsXml_); } // Missing settings file
    }
}


Answer 2:

一些改进:

1)装载了一下简单的,不需要其他线路:

var config = ConfigurationManager.OpenExeConfiguration(...);

2)访问AppSettings正确:

config.AppSettings.Settings[...]; // and other things under AppSettings

3)如果你想有一个自定义配置部分,使用这个工具: http://csd.codeplex.com/



Answer 3:

我从来没有最终得到的配置管理方法的工作。 花了半天得过且过,没有取得进展后,我决定为我的需要是基本的推出自己的解决方案。

这里是我想出了最终解决方案:

public class Settings
{
    private XmlDocument _xmlDoc;
    private XmlNode _settingsNode;
    private string _path;

    public Settings(string path)
    {
        _path = path;
        LoadConfig(path);
    }

    private void LoadConfig(string path)
    {
       //TODO: add error handling
        _xmlDoc = null;
        _xmlDoc = new XmlDocument();
        _xmlDoc.Load(path);
        _settingsNode = _xmlDoc.SelectSingleNode("//appSettings");
    }

    //
    //use the same structure as in .config appSettings sections
    //
    public string this[string s]
    {
        get
        {
            XmlNode n = _settingsNode.SelectSingleNode(String.Format("//add[@key='{0}']", s));
            return n != null ? n.Attributes["value"].Value : null;
        }
        set
        {
            XmlNode n = _settingsNode.SelectSingleNode(String.Format("//add[@key='{0}']", s));

            //create the node if it doesn't exist
            if (n == null)
            {
                n=_xmlDoc.CreateElement("add");
                _settingsNode.AppendChild(n);
                XmlAttribute attr =_xmlDoc.CreateAttribute("key");
                attr.Value = s;
                n.Attributes.Append(attr);
                attr = _xmlDoc.CreateAttribute("value");
                n.Attributes.Append(attr);
            }

            n.Attributes["value"].Value = value;
            _xmlDoc.Save(_path);
        }
    }
}


文章来源: Reading and writing values in.NET .config files