修改配置文件中的密钥c#
Modifying key in config file c#
我有一个程序读取 app.config 并将以编程方式更新配置文件。
例如:
<appSettings>
<add key = "card" value = "rare" />
<add key = "game" value = "poker" />
</appSettings>
更新配置文件后,应该变成这样:
<appSettings>
<add key = "drink" value = "rare" />
<add key = "game" value = "poker" />
</appSettings>
我知道我可以删除旧的键和值并添加新的。
但它总是添加到最后一个索引。
我需要它与我进行更改的索引完全相同。
抱歉不好的类比和不好的英语。
class Program
{
static void Main(string[] args)
{
//UpdateSetting("language", "English");
UpdateAppSettings("card", "drink", "water");
}
public static void UpdateAppSettings(string OldKeyName, string KeyName, string KeyValue)
{
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "appSettings")
{
foreach (XmlNode xNode in xElement.ChildNodes)
{
if (xNode.Attributes[0].Value == OldKeyName)
{
xNode.Attributes[0].Value = KeyName;
xNode.Attributes[1].Value = KeyValue;
}
}
}
}
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
Remember not to test it from VS debugger. You should build in release mode and open that execute that binary from that folder to check the changes made to that app.config appsettings file.
我有一个程序读取 app.config 并将以编程方式更新配置文件。
例如:
<appSettings>
<add key = "card" value = "rare" />
<add key = "game" value = "poker" />
</appSettings>
更新配置文件后,应该变成这样:
<appSettings>
<add key = "drink" value = "rare" />
<add key = "game" value = "poker" />
</appSettings>
我知道我可以删除旧的键和值并添加新的。 但它总是添加到最后一个索引。
我需要它与我进行更改的索引完全相同。
抱歉不好的类比和不好的英语。
class Program
{
static void Main(string[] args)
{
//UpdateSetting("language", "English");
UpdateAppSettings("card", "drink", "water");
}
public static void UpdateAppSettings(string OldKeyName, string KeyName, string KeyValue)
{
XmlDocument XmlDoc = new XmlDocument();
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "appSettings")
{
foreach (XmlNode xNode in xElement.ChildNodes)
{
if (xNode.Attributes[0].Value == OldKeyName)
{
xNode.Attributes[0].Value = KeyName;
xNode.Attributes[1].Value = KeyValue;
}
}
}
}
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
Remember not to test it from VS debugger. You should build in release mode and open that execute that binary from that folder to check the changes made to that app.config appsettings file.