如何更改自定义 configSections 变量的值?
How can I change the value of a custom configSections variable?
我的 App.config 文件的 configSections 中有一个自定义部分,如何在代码中更改此部分的其中一个变量的值?
我想更改的部分是"serverConfiguration",我想更改"serverUrl"的值:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="serverConfiguration" type="someType" />
</configSections>
<serverConfiguration serverUrl="http://development/server/" />
</configuration>
我从上一个问题 App.Config change value 中找到了下面这段代码。
它看起来很接近我的需要,但我不确定如何自己更改它以将其用于自定义部分而不是 AppSettings。下面的代码是否适用于我正在尝试做的事情?我如何更改下面的代码以允许我将这个新字符串作为 serverUrl“http://staging/server/”传递?谢谢!
class Program
{
static void Main(string[] args)
{
UpdateSetting("lang", "Russian");
}
private static void UpdateSetting(string key, string value)
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
}
您可以选择将配置加载到 XML、编辑节点值并将其保存回来。试试这个
var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
xmlDoc.SelectSingleNode("//serverConfiguration").Attributes["serverUrl"].Value = "http://staging/server/";
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
保存文件后刷新配置部分可能是个好主意。
我的 App.config 文件的 configSections 中有一个自定义部分,如何在代码中更改此部分的其中一个变量的值?
我想更改的部分是"serverConfiguration",我想更改"serverUrl"的值:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="serverConfiguration" type="someType" />
</configSections>
<serverConfiguration serverUrl="http://development/server/" />
</configuration>
我从上一个问题 App.Config change value 中找到了下面这段代码。 它看起来很接近我的需要,但我不确定如何自己更改它以将其用于自定义部分而不是 AppSettings。下面的代码是否适用于我正在尝试做的事情?我如何更改下面的代码以允许我将这个新字符串作为 serverUrl“http://staging/server/”传递?谢谢!
class Program
{
static void Main(string[] args)
{
UpdateSetting("lang", "Russian");
}
private static void UpdateSetting(string key, string value)
{
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
}
您可以选择将配置加载到 XML、编辑节点值并将其保存回来。试试这个
var xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
xmlDoc.SelectSingleNode("//serverConfiguration").Attributes["serverUrl"].Value = "http://staging/server/";
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
保存文件后刷新配置部分可能是个好主意。