ConfigurationManager中可以保留在保存XML评论()?
-
21-09-2019 - |
题
我写了一个小工具,可以让我改变了另一个应用程序的App.config文件简单AppSetting,然后保存更改:
//save a backup copy first.
var cfg = ConfigurationManager.OpenExeConfiguration(pathToExeFile);
cfg.SaveAs(cfg.FilePath + "." + DateTime.Now.ToFileTime() + ".bak");
//reopen the original config again and update it.
cfg = ConfigurationManager.OpenExeConfiguration(pathToExeFile);
var setting = cfg.AppSettings.Settings[keyName];
setting.Value = newValue;
//save the changed configuration.
cfg.Save(ConfigurationSaveMode.Full);
这个工作得很好,除了一个副作用。 新保存的config文件丢失所有的原始XML注释,但只有AppSettings的区域内。是否有可能保留原始配置文件的AppSettings区XML注释?
解决方案
我跳进Reflector.Net看着这个类的反编译的源。简短的回答是否定的,它不会保留意见。微软写的类的方法是从生成的配置类属性的XML文档。由于意见不配置类显示出来,他们不让它回到XML。
和什么使这更糟糕的是,微软封闭所有这些类的,所以你不能派生新类,并插入自己的实现。你唯一的选择是将评论appSettings部分之外,或使用XmlDocument
或XDocument
类,而不是解析配置文件。
对不起。这是一个边缘的情况下,微软只是没有进行规划。
其他提示
下面是你可以用它来保存意见的样本函数。它可以让你同时编辑一个键/值对。我还添加了一些东西来格式化很好基于我经常使用的文件的方式文件(你可以很容易地删除,如果你想)。我希望这可以帮助别人,将来别人。
public static bool setConfigValue(Configuration config, string key, string val, out string errorMsg) {
try {
errorMsg = null;
string filename = config.FilePath;
//Load the config file as an XDocument
XDocument document = XDocument.Load(filename, LoadOptions.PreserveWhitespace);
if(document.Root == null) {
errorMsg = "Document was null for XDocument load.";
return false;
}
XElement appSettings = document.Root.Element("appSettings");
if(appSettings == null) {
appSettings = new XElement("appSettings");
document.Root.Add(appSettings);
}
XElement appSetting = appSettings.Elements("add").FirstOrDefault(x => x.Attribute("key").Value == key);
if (appSetting == null) {
//Create the new appSetting
appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", val)));
}
else {
//Update the current appSetting
appSetting.Attribute("value").Value = val;
}
//Format the appSetting section
XNode lastElement = null;
foreach(var elm in appSettings.DescendantNodes()) {
if(elm.NodeType == System.Xml.XmlNodeType.Text) {
if(lastElement?.NodeType == System.Xml.XmlNodeType.Element && elm.NextNode?.NodeType == System.Xml.XmlNodeType.Comment) {
//Any time the last node was an element and the next is a comment add two new lines.
((XText)elm).Value = "\n\n\t\t";
}
else {
((XText)elm).Value = "\n\t\t";
}
}
lastElement = elm;
}
//Make sure the end tag for appSettings is on a new line.
var lastNode = appSettings.DescendantNodes().Last();
if (lastNode.NodeType == System.Xml.XmlNodeType.Text) {
((XText)lastNode).Value = "\n\t";
}
else {
appSettings.Add(new XText("\n\t"));
}
//Save the changes to the config file.
document.Save(filename, SaveOptions.DisableFormatting);
return true;
}
catch (Exception ex) {
errorMsg = "There was an exception while trying to update the config value for '" + key + "' with value '" + val + "' : " + ex.ToString();
return false;
}
}
如果评论是至关重要的,它可能只是你唯一的选择是阅读和手动保存文件(通过XmlDocument
或新的LINQ相关的API)。然而,如果这些意见并不重要,我要么让他们去或可能考虑将它们嵌入的(虽然冗余)的数据元素。
不隶属于 StackOverflow