当我想保存配置时,我通常使用XMLSerializer。它很容易使用和理解。最后,您只需将反序列化的对象强制转换为某个类型。就是这样。太完美了。
现在我必须学习整个System.Configuration-事情,我既不知道从哪里开始,也不知道它到底做了什么。只有一大堆“部分”、“映射”之类的东西。我该怎么处理呢?MSDN-文章再一次没有解释我用这个做了什么。对于做一件非常简单的事情来说,这似乎是很多不必要的开销。
发布于 2014-02-03 23:32:33
您是在谈论应用程序配置类中的自定义部分吗?here it is described when derived from MS Configuration section
此外,还可以定义自己的自定义配置节处理程序IConfigurationSectionHandler,该处理程序将获取XML并将其反序列化为某个类值。
如果您想得到更具体的答案,请提出更具体的问题
从配置文件加载更新当您从ConfigurationSection派生时,可以使用如下代码
Configuration config;
config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
var _current = (ClassSettings)config.GetSection(sectionName);如果您使用了自定义配置节处理程序(IConfigurationSectionHandler),则可以使用如下代码加载类实例:
var database = (DatabaseSettings)ConfigurationManager.GetSection(databaseSettingsName);不幸的是,写入配置文件要棘手得多。
MS建议this way更新配置文件内容
或者,您可以像打开任何其他XML文档一样打开配置文件,并像更新任何其他XML文档一样对其进行更新:
XmlDocument config = new XmlDocument();
string configName = Assembly.GetExecutingAssembly().Location + ".config";
config.Load(configName);
XmlNode databaseNode = config.DocumentElement.SelectSingleNode(sectionName + "/" + DatabaseName);
if (databaseNode != null)
{
databaseNode.Attributes[Database.PasswordName].Value = value.Database.PasswordEnc;
}
//another nodes changes are skipped
config.Save(configName);但是,您可以使用Protect section方法对配置文件中的节进行加密:
var config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
ConfigurationSection section = config.Sections[sectionName];
if (section != null)
{
var info = section.SectionInformation;
var pr = info.IsProtected;
if (pr)
info.UnprotectSection();
res = GetSettingsSection<T>(sectionName, value);
if (!pr)
{
info.ProtectSection("DataProtectionConfigurationProvider");
config.Save();
}
}也可以打开配置文件,比如XML,序列化你的设置类实例,用新的元素替换旧的元素(配置节)。
不幸的是,我不能说使用MS app.config风格有很多好处。这是另一个抽象层和一些附加功能(保护/取消保护部分,从用户或机器存储加载文件,等等)。
对于ASP应用程序,配置文件是组合的-可以使用应用程序web.config扩展机器web.config设置。
对于小的winforms应用,我更喜欢使用JSON序列化配置文件-它不像MS app.config那样包含任何开销,并且没有XMLSerializer问题(比如性能问题)
https://stackoverflow.com/questions/21529589
复制相似问题