2

.NETにデフォルトの場所から読み取らせるのではなく、user.configファイルにカスタムパスを使用したい。

私はこのようにファイルを開いています:

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

しかし、実際に設定を読み取る方法がわかりません。AppDataまたはConfigurationSectionから値を取得しようとすると、値にアクセスできないというコンパイルエラーが発生します。

データを適切に消費するために、ある種のラッパークラスを作成する必要がありますか?

4

3 に答える 3

2

最近、同様の問題が発生しました。設定ファイルが読み込まれる場所を、AppDataのデフォルトの場所からApplicationディレクトリに変更する必要がありました。私の解決策は、カスタムSettingsProviderを指定したApplicationSettingsBaseから派生した独自の設定ファイルを作成することでした。ソリューションは最初はやり過ぎのように感じましたが、予想よりも柔軟で保守しやすいことがわかりました。

アップデート:

サンプル設定ファイル:

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
    }
}
于 2012-05-06T03:46:43.907 に答える
1

いくつかの改善:

1)少し簡単にロードします。他の行は必要ありません。

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

AppSettings2)適切にアクセスする:

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

3)カスタム構成セクションが必要な場合は、次のツールを使用してください:http: //csd.codeplex.com/

于 2012-05-05T21:51:16.543 に答える
0

ConfigurationManagerのアプローチが機能するようになることはありませんでした。何の進展もなく半日混乱した後、私は自分のニーズが基本であるため、独自のソリューションを展開することにしました。

これが私が最終的に思いついた解決策です:

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);
        }
    }
}
于 2012-05-06T13:34:28.370 に答える