我的应用程序被分成一个配置工具,它写入配置和观众刚刚读取并配置使用设置。
会会在这种情况下存储推荐的属性有什么技巧? 将XML对于不同类别是一个好主意?
该应用程序是用C#开发,在.NET 3.5和使用的WinForms。
我的应用程序被分成一个配置工具,它写入配置和观众刚刚读取并配置使用设置。
会会在这种情况下存储推荐的属性有什么技巧? 将XML对于不同类别是一个好主意?
该应用程序是用C#开发,在.NET 3.5和使用的WinForms。
我想有一个共享程序集,其中包含您的设置类。 然后,您可以序列化/反序列化这个类到硬盘驱动器上的一个共同的地方:
[XmlRoot()]
public class Settings
{
private static Settings instance = new Settings();
private Settings() {}
/// <summary>
/// Access the Singleton instance
/// </summary>
[XmlElement]
public static Settings Instance
{
get
{
return instance;
}
}
/// <summary>
/// Gets or sets the height.
/// </summary>
/// <value>The height.</value>
[XmlAttribute]
public int Height { get; set; }
/// <summary>
/// Main window status (Maximized or not)
/// </summary>
[XmlAttribute]
public FormWindowState WindowState
{
get;
set;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="Settings"/> is offline.
/// </summary>
/// <value><c>true</c> if offline; otherwise, <c>false</c>.</value>
[XmlAttribute]
public bool IsSomething
{
get;
set;
}
/// <summary>
/// Save setting into file
/// </summary>
public static void Serialize()
{
// Create the directory
if (!Directory.Exists(AppTmpFolder))
{
Directory.CreateDirectory(AppTmpFolder);
}
using (TextWriter writer = new StreamWriter(SettingsFilePath))
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
serializer.Serialize(writer, Settings.Instance);
}
}
/// <summary>
/// Load setting from file
/// </summary>
public static void Deserialize()
{
if (!File.Exists(SettingsFilePath))
{
// Can't find saved settings, using default vales
SetDefaults();
return;
}
try
{
using (XmlReader reader = XmlReader.Create(SettingsFilePath))
{
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
if (serializer.CanDeserialize(reader))
{
Settings.instance = serializer.Deserialize(reader) as Settings;
}
}
}
catch (System.Exception)
{
// Failed to load some data, leave the settings to default
SetDefaults();
}
}
}
然后,您的XML文件将是这样的:
<?xml version="1.0" encoding="utf-8"?>
<Settings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Height="738" WindowState="Maximized" IsSomething="false" >
</Settings>
XML似乎为这个理想的选择。
在的WinForms用户设置通过XML,所以你有你需要的所有类和辅助方法仍然存在。