Ładowanie właściwości. Ustawienia z innego pliku w czasie wykonywania

Czy istnieje sposób załadowania ustawień z innego pliku niż domyślnyApp.config plik w czasie wykonywania? Chciałbym to zrobić po załadowaniu domyślnego pliku konfiguracyjnego.

używamSettings.Settings GUI w Visual Studio do tworzenia mojegoApp.config plik dla mnie. Plik konfiguracyjny wygląda tak:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
            <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
        <section name="SnipetTester.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
    </configSections>
      <applicationSettings>
        <SnipetTester.Properties.Settings>
          <setting name="SettingSomething" serializeAs="String">
            <value>1234</value>
          </setting>
        </SnipetTester.Properties.Settings>
      </applicationSettings>
    </configuration>

W kodzie mogę uzyskać dostęp do takich ustawień:

Console.WriteLine("Default setting value:  " + Properties.Settings.Default.SettingSomething);

Chodzi o to, że gdy aplikacja jest uruchomiona, powinienem móc określić plik konfiguracyjny w czasie wykonywania i załadować plik konfiguracyjny do aplikacjiProperties.Settings.Default obiekt zamiast używać domyślnegoapp.config plik. Formaty plików konfiguracyjnych byłyby takie same, ale wartości ustawień byłyby inne.

Wiem, jak to zrobić za pomocąConfigurationManager.OpenExeConfiguration(configFile);. Jednak w testach, które uruchomiłem, nie aktualizujeProperties.Settings.Default obiekt odzwierciedlający nowe wartości z pliku konfiguracyjnego.

Po dłuższym zastanowieniu się nad tym, udało mi się znaleźć rozwiązanie, które lubię trochę lepiej. Jestem pewien, że ma pewne pułapki, ale myślę, że zadziała to, czego potrzebuję.

ZasadniczoProperties.Settings klasa jest automatycznie generowana przez Visual Studio; generuje dla ciebie kod klasy. Udało mi się ustalić, gdzie został wygenerowany kod i dodać kilka wywołań funkcji, aby samodzielnie załadować plik konfiguracyjny. Oto mój dodatek:

internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase 
{
    //Parses a config file and loads its settings
    public void Load(string filename)
    {
        System.Xml.Linq.XElement xml = null;
        try
        {
            string text = System.IO.File.ReadAllText(filename);
            xml = System.Xml.Linq.XElement.Parse(text);
        }
        catch
        {
            //Pokemon catch statement (gotta catch 'em all)

            //If some exception occurs while loading the file,
            //assume either the file was unable to be read or
            //the config file is not in the right format.
            //The xml variable will be null and none of the
            //settings will be loaded.
        }

        if(xml != null)
        {
            foreach(System.Xml.Linq.XElement currentElement in xml.Elements())
            {
                switch (currentElement.Name.LocalName)
                {
                    case "userSettings":
                    case "applicationSettings":
                        foreach (System.Xml.Linq.XElement settingNamespace in currentElement.Elements())
                        {
                            if (settingNamespace.Name.LocalName == "SnipetTester.Properties.Settings")
                            {
                                foreach (System.Xml.Linq.XElement setting in settingNamespace.Elements())
                                {
                                    LoadSetting(setting);
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    //Loads a setting based on it's xml representation in the config file
    private void LoadSetting(System.Xml.Linq.XElement setting)
    {
        string name = null, type = null, value = null;

        if (setting.Name.LocalName == "setting")
        {
            System.Xml.Linq.XAttribute xName = setting.Attribute("name");
            if (xName != null)
            {
                name = xName.Value;
            }

            System.Xml.Linq.XAttribute xSerialize = setting.Attribute("serializeAs");
            if (xSerialize != null)
            {
                type = xSerialize.Value;
            }

            System.Xml.Linq.XElement xValue = setting.Element("value");
            if (xValue != null)
            {
                value = xValue.Value;
            }
        }


        if (string.IsNullOrEmpty(name) == false &&
            string.IsNullOrEmpty(type) == false &&
            string.IsNullOrEmpty(value) == false)
        {
            switch (name)
            {
                //One of the pitfalls is that everytime you add a new
                //setting to the config file, you will need to add another
                //case to the switch statement.
                case "SettingSomething":
                    this[name] = value;
                    break;
                default:
                    break;
            }
        }
    }
}

Dodany kod ujawniaProperties.Settings.Load(string filename) funkcjonować. Funkcja przyjmuje nazwę pliku konfiguracyjnego jako parametr. Sparsuje plik i załaduje wszystkie ustawienia, które napotka w pliku konfiguracyjnym. Aby powrócić do pierwotnej konfiguracji, po prostu zadzwońProperties.Settings.Reload().

Mam nadzieję, że to pomoże komuś innemu!

questionAnswers(3)

yourAnswerToTheQuestion