我有以下内容,但它不适合我:
static void SaveVersion(string configFile, string Version)
{
XmlDocument config = new XmlDocument();
config.Load(configFile);
XmlNode appSettings = config.SelectSingleNode("configuration/appSettings");
XmlNodeList appKids = appSettings.ChildNodes;
foreach (XmlNode setting in appKids)
{
if (setting.Attributes["key"].Value == "AgentVersion")
setting.Attributes["value"].Value = Version;
}
config.Save(configFile);
}
我在 config.Load(configFile) 上加载的配置文件如下:
<?xml version="1.0"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" />
</startup>
<appSettings>
<add key="AgentVersion" value="2.0.5" />
<add key="ServerHostName" value="" />
<add key="ServerIpAddress" value="127.0.0.1" />
<add key="ServerPort" value="9001" />
</appSettings>
</configuration>
我错过了什么吗?我认为它只会编辑特定的属性 AgentVersion
但它并没有真正做任何事情。
最佳答案
您知道ConfigurationManager
吗?类(class)?您可以使用它来操作您的 app.config
文件,而无需手动执行任何操作。我认为你不应该重新发明轮子,除非你有充分的理由:
static void SaveVersion(string configFile, string version)
{
var myConfig = ConfigurationManager.OpenExeConfiguration(configFile);
myConfig.AppSettings.Settings["AgentVersion"].Value = version;
myConfig.Save();
}
关于c# - 仅写入一个 XML 属性,而不影响其余属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17179090/