Esiste un modo per caricare le impostazioni da un file diverso dal file App.config
predefinito in fase di runtime? Mi piacerebbe farlo dopo che è stato caricato il file di configurazione di default.Caricamento proprietà. Impostazioni da un file diverso in fase di esecuzione
Io uso la GUI Settings.Settings
in Visual Studio per creare il mio file App.config
per me. Il file di configurazione finisce per assomigliare a questo:
<?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>
In codice, sono in grado di accedere alle impostazioni in questo modo:
Console.WriteLine("Default setting value: " + Properties.Settings.Default.SettingSomething);
L'idea è che quando si esegue l'applicazione, dovrei essere in grado di specificare un file di configurazione in fase di esecuzione e di caricare l'applicazione nel file di configurazione nell'oggetto Properties.Settings.Default
invece di utilizzare il file predefinito app.config
. I formati dei file di configurazione sarebbero gli stessi, ma i valori delle impostazioni sarebbero diversi.
Conosco un modo per farlo con ConfigurationManager.OpenExeConfiguration(configFile);
. Tuttavia, nei test che ho eseguito, non aggiorna l'oggetto Properties.Settings.Default
per riflettere i nuovi valori dal file di configurazione.
Dopo pensando a questo un po 'più a lungo, sono stato in grado di trovare una soluzione che mi piace un po' meglio. Sono sicuro che ha alcune insidie, ma penso che funzionerà per quello che ho bisogno di fare.
In sostanza, la classe Properties.Settings
viene generata automaticamente da Visual Studio; genera il codice per la classe per te. Sono stato in grado di trovare dove è stato generato il codice e aggiungere alcune chiamate di funzione per caricare un file di configurazione da solo. Ecco la mia aggiunta:
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;
}
}
}
}
Il codice ho aggiunto espone una funzione Properties.Settings.Load(string filename)
. La funzione accetta un nome file di configurazione come parametro. Analizzerà il file e caricherà tutte le impostazioni che incontra nel file di configurazione. Per ripristinare la configurazione originale, è sufficiente chiamare Properties.Settings.Reload()
.
Spero che questo possa aiutare qualcun altro!
questo sembra davvero promettente, ma come possiamo usare i tipi – tofutim