在WinForms中使用XML配置文件持久化数据(保存和恢复用户和应用程序数据)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在WinForms中使用XML配置文件持久化数据(保存和恢复用户和应用程序数据)相关的知识,希望对你有一定的参考价值。
References: [msdn blog](http://blogs.msdn.com/youssefm/archive/2010/01/21/how-to-change-net-configuration-files-at-runtime-including-for-wcf.aspx), [devX](http://www.devx.com/dotnet/Article/41639/0/page/1)The .NET framework provides XML configuration files (in the Properties->Settings area of a C# project or in app.config) which make it easy to bind and save/restore data between application executions. I want to take it one step further and allow the user to save and restore multiple versions of these config files, rather than just relying on the last-entered data.
To get a file with any saved user settings, do this:
internal static void Export(string settingsFilePath)
{
Properties.Settings.Default.Save();
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
config.SaveAs(settingsFilePath);
}
The ConfigurationUserLevel setting is important; it determines whether you get the file you see in Settings.settings or the file which has the user's custom data.
(See example output file in source, as it won't show up correctly here.)
To import the settings in a file, you can use the Import method below. [EDIT: This is the old method which only works for settings persisted as strings. The Import code in the Source window is much better and more robust. I'm just leaving this in for reference.]
internal static void Import(string settingsFilePath)
{
if (!File.Exists(settingsFilePath))
{
throw new FileNotFoundException();
}
var appSettings = Properties.Settings.Default;
try
{
// Open settings file as XML
var import = XDocument.Load(settingsFilePath);
// Get the elements
var settings = import.XPathSelectElements("//setting");
foreach (var setting in settings)
{
string name = setting.Attribute("name").Value;
string value = setting.XPathSelectElement("value").FirstNode.ToString();
try
{
appSettings[name] = value; // throws SettingsPropertyNotFoundException
}
catch (SettingsPropertyNotFoundException spnfe)
{
_logger.WarnException("An imported setting ({0}) did not match an existing setting.".FormatString(name), spnfe);
}
}
}
catch (Exception exc)
{
_logger.ErrorException("Could not import settings.", exc);
appSettings.Reload(); // from last set saved, not defaults
}
}
References:
[My question on StackOverflow](http://stackoverflow.com/questions/1869628/how-to-use-net-configuration-files-app-config-settings-settings-to-save-and-r)
http://articles.techrepublic.com.com/5100-10878_11-1044975.html
http://chiragrdarji.wordpress.com/2008/09/25/how-to-change-appconfig-file-run-time-using-c/
http://msdn.microsoft.com/en-us/library/system.configuration.configuration.aspx
http://stackoverflow.com/questions/132544/net-configuration-app-config-web-config-settings-settings
[Saving Settings in .NET 2.0 Apps](http://www.ddj.com/windows/187002743)
Exported file: <?xml version="1.0" encoding="utf-8"?> <configuration> <userSettings> <HawkConfigGUI.Properties.Settings> <setting name="FpgaFilePath" serializeAs="String"> <value>testfpga</value> </setting> <setting name="FirmwareFilePath" serializeAs="String"> <value>test</value> </setting> </HawkConfigGUI.Properties.Settings> </userSettings> </configuration> Class: using System; using System.Configuration; using System.IO; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; public static class SettingsIO { internal static void Import(string settingsFilePath) { if (!File.Exists(settingsFilePath)) { } var appSettings = Properties.Settings.Default; try { var config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.PerUserRoamingAndLocal); string appSettingsXmlName = Properties.Settings.Default.Context["GroupName"].ToString(); // returns "MyApplication.Properties.Settings"; // Open settings file as XML var import = XDocument.Load(settingsFilePath); // Get the whole XML inside the settings node var settings = import.XPathSelectElements("//" + appSettingsXmlName); config.GetSectionGroup("userSettings") .Sections[appSettingsXmlName] .SectionInformation .SetRawXml(settings.Single().ToString()); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("userSettings"); appSettings.Reload(); } catch (Exception) // Should make this more specific { // Could not import settings. appSettings.Reload(); // from last set saved, not defaults } } internal static void Export(string settingsFilePath) { Properties.Settings.Default.Save(); var config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.PerUserRoamingAndLocal); config.SaveAs(settingsFilePath); } }
以上是关于在WinForms中使用XML配置文件持久化数据(保存和恢复用户和应用程序数据)的主要内容,如果未能解决你的问题,请参考以下文章
Apache ActiveMQ 持久化到MySQL数据库的简单配置
当使用 WinForms 提取数据时,XML 会转换为纯文本。有没有办法维护 XML,或将其转换回 C#?