28

我编写了一个小实用程序,允许我为另一个应用程序的 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 注释?

如果您想快速编译和运行它,这里是完整源代码的 pastebin。

4

3 回答 3

31

我跳进 Reflector.Net 并查看了这个类的反编译源。简短的回答是否定的,它不会保留评论。Microsoft 编写该类的方式是根据配置类的属性生成 XML 文档。由于注释不会出现在配置类中,它们不会将其返回到 XML 中。

更糟糕的是,Microsoft 密封了所有这些类,因此您无法派生新类并插入您自己的实现。您唯一的选择是将注释移到 AppSettings 部分之外,或者使用XmlDocumentorXDocument类来解析配置文件。

对不起。这是微软没有计划的一个边缘案例。

于 2009-12-29T00:39:17.623 回答
4

这是一个示例函数,您可以使用它来保存评论。它允许您一次编辑一个键/值对。我还添加了一些东西来根据我通常使用文件的方式很好地格式化文件(如果你愿意,你可以很容易地删除它)。我希望这可能会在未来对其他人有所帮助。

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;
    }
}
于 2015-11-13T19:33:59.793 回答
2

如果评论很重要,那么您唯一的选择可能是手动读取和保存文件(通过XmlDocument或新的 Linq 相关 API)。但是,如果这些评论不重要,我要么放手,要么考虑将它们嵌入(尽管是多余的)数据元素。

于 2009-12-27T19:38:55.193 回答