讓我們假設你有一個包含settings.xml
文件的地方:
<?xml version="1.0" encoding="utf-8" ?>
<Settings>
<Section1>
<Key1>Value1</Key1>
<Key2>Value2</Key2>
</Section1>
<Section2>
<Key1>Value3</Key1>
<Key2>Value4</Key2>
<KeyX>Value5</KeyX>
</Section2>
</Settings>
然後你就可以有一個SettingsProvider
類是這樣的:
using System.Xml.Linq;
public static class SettingsProvider
{
private const string settingsFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "settings.xml");
private static XDocument settings;
static SettingsProvider()
{
try
{
settings = XDocument.Load(settingsFileName);
}
catch
{
settings = XDocument.Parse("<Settings/>");
}
}
public static string GetValue(string section, string key, string defaultValue)
{
XElement settingElement = GetSettingElement(section, key);
return settingElement == null ? defaultValue : settingElement.Value;
}
public static void SetValue(string section, string key, string value)
{
XElement settingElement = GetSettingElement(section, key, true);
settingElement.Value = value;
settings.Save(settingsFileName);
}
private static XElement GetSettingElement(string section, string key, bool createIfNotExist = false)
{
XElement sectionElement =
settings
.Root
.Elements(section)
.FirstOrDefault();
if (sectionElement == null)
{
if (createIfNotExist)
{
sectionElement = new XElement(section);
settings.Root.Add(sectionElement);
}
else
{
return null;
}
}
XElement settingElement =
sectionElement
.Elements(key)
.FirstOrDefault();
if (settingElement == null)
{
if (createIfNotExist)
{
settingElement = new XElement(key);
sectionElement.Add(settingElement);
}
}
return settingElement;
}
public static void RemoveSetting(string section, string key)
{
XElement settingElement = GetSettingElement(section, key);
if (settingElement == null)
{
return;
}
XElement sectionElement = settingElement.Parent;
settingElement.Remove();
if (sectionElement.IsEmpty)
{
sectionElement.Remove();
}
settings.Save(settingsFileName);
}
}
您可以使用它像這樣:
string section1Key1 = SettingsProvider.GetValue("Section1", "Key1", "default");
SettingsProvider.SetValue("Section1", "Key1", "OtherValue");
SettingsProvider.SetValue("Section1", "Key2", "Value2");
SettingsProvider.SetValue("Section2", "Key1", "Value3");
SettingsProvider.RemoveSetting("Section2", "Key1");
SettingsProvider.RemoveSetting("Section1", "Key2");
這很棒。我只修改路徑以使其有效,並且如果文件不存在,還必須添加初始化方法以創建空根元素。查看我的修改建議。 Köszönömszépen;-) – ib11
接受您的修改建議。但將Initialize()方法替換爲靜態ctor以確保在使用'SettingsProvider'之前執行初始化。 Igazánnincs mit,énköszönöm。 :) – Gabor
好的,它首先被執行,因爲'GetSettingElement'總是被首先調用,它首先有'Initialize()'方法調用。但這是更清潔的。我只做了一個更多的編輯,以刪除不再需要的調用(並且因爲您將方法更改爲構造函數而無效)。 Ha tetszik akérdés,azt is felpontozhatod ;-)Köszimégegyszer,sokatsegített。 – ib11