using System;
using System.Xml;
using System.Windows.Forms;
using System.Configuration;
using System.IO;
using System.Reflection;
namespace System.Configuration
{
public class ConfigurationSettings
{
private static string configFileName;
private const string DEFAULT_SECTION = "appSettings";
static ConfigurationSettings()
{
string AppPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
string EXEName = Assembly.GetExecutingAssembly().GetName().Name;
configFileName = Path.Combine(AppPath, EXEName) + ".exe.config";
}
public static string Get(string Key)
{
return Get(Key, DEFAULT_SECTION);
}
public static string Get(string Key, string Section)
{
string str = string.Empty;
XmlDocument doc = new XmlDocument();
doc.Load(configFileName);
string nodeKey = "//" + Section + "/add[@key='" + Key + "']/@value";
if (doc.DocumentElement.SelectSingleNode(nodeKey) != null)
str = doc.DocumentElement.SelectSingleNode(nodeKey).Value;
return str;
}
public static void Set(string Key, string Value)
{
Set(Key, DEFAULT_SECTION, Value);
}
public static void Set(string Key, string Section, string Value)
{
XmlDocument doc = new XmlDocument();
doc.Load(configFileName);
string nodeKey = "//" + Section + "/add[@key='" + Key + "']/@value";
if (doc.DocumentElement.SelectSingleNode(nodeKey) != null)
{
doc.DocumentElement.SelectSingleNode(nodeKey).Value = Value;
}
else
{
XmlElement add = doc.CreateElement("add");
XmlAttribute attrkey = doc.CreateAttribute("key");
attrkey.Value = Key;
XmlAttribute val = doc.CreateAttribute("value");
val.Value = Value;
add.Attributes.Append(attrkey);
add.Attributes.Append(val);
doc.DocumentElement.SelectSingleNode("//" + Section).AppendChild(add);
}
doc.Save(configFileName);
}
}
}
Questo codice consente di gestire file di configurazione con il seguente formato:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SettingName" value="SettingValue" />
</appSettings>
</configuration>
//Legge un valore.
string value = ConfigurationSettings.Get("SettingName");
//Scrive un valore.
ConfigurationSettings.Set("SettingName", "NewValue");