版本:
VS2015
Revit2018
实现功能:
直接获取指定sectionGroup下sectionName的值,并实现修改;
对C盘下生成的.config文件进行修改(生成程序产生的.config文件并没有做出修改)。
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="Group">
<section name="CO" type="System.Configuration.AppSettingsSection"/>
</sectionGroup>
</configSections>
<Group>
<CO>
<add key="ABC" value="abcd" />
<add key="DEF" value="False" />
<add key="GHI" value="1" />
</CO>
</Group>
</configuration>
关键代码
#region 测试4:直接获取指定sectionGroup下sectionName的值
string groupName = "Group";
string sectionName = "CO";
string key = "ABC";
//获取Configuration对象
string assemblyPath = this.GetType().Assembly.Location;
MessageBox.Show(assemblyPath, "1");
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config = ConfigurationManager.OpenExeConfiguration(assemblyPath);
//访问指定section
string BBB = String.Format("{0}{1}{2}", groupName, "/", sectionName);
ConfigurationSection AAA = config.GetSection(BBB);
if (AAA.SectionInformation.Name == sectionName)
{
MessageBox.Show("OK", "4");//成功
AppSettingsSection section = AAA as AppSettingsSection;
//添加
section.Settings.Add("cheng", "aaaaa");
//修改
section.Settings["cheng"].Value = "成功了!";
删除
//section.Settings.Remove("cheng");
MessageBox.Show("666", "5");//成功
foreach (KeyValueConfigurationElement keyvalue in section.Settings)
{
if (keyvalue.Key.ToString() == key)
{
MessageBox.Show(keyvalue.Key + ":" + keyvalue.Value, "7");
}
}
}
config.Save();
#endregion