尝试循环访问app.config文件,搜索帖子但没有运气
app.config
<configSections>
<section name="US" type="System.Configuration.NameValueSectionHandler"/>
<section name="UK" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<US>
<add key="UserName" value="test" />
<add key="Password" value="test" />
<add key="baseURI" value="http://test.com />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</US>
<UK>
<add key="UserName" value="test1 />
<add key="Password" value="test1 />
<add key="baseURI" value="http://test1.com />
<add key="ClientSettingsProvider.ServiceUri" value="" />
</UK>
我需要遍历app.config文件并获取美国和英国部分的关键值数据,如下所示。
*Result:*
Section : US
Username: test
Password: test
baseURI: http://test.com
Section : UK
Username: test1
Password: test1
baseURI: http://test1.com
答案 0 :(得分:0)
yr配置文件存在一些问题,你缺少一些引号(“),plz首先纠正它。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!--This MUST be the first node-->
<configSections>
<section name="US" type="System.Configuration.AppSettingsSection"/>
<section name="UK" type="System.Configuration.AppSettingsSection"/>
</configSections>
<US>
<add key="UserName" value="test" />
<add key="Password" value="test" />
<add key="baseURI" value="http://test.com" /> <!--misssing a " here!! -->
<add key="ClientSettingsProvider.ServiceUri" value="" />
</US>
<UK>
<add key="UserName" value="test1" /><!--misssing a " here!! -->
<add key="Password" value="test1" /><!--misssing a " here!! -->
<add key="baseURI" value="http://test1.com" /><!--misssing a " here!! -->
<add key="ClientSettingsProvider.ServiceUri" value="" />
</UK>
</configuration>
然后在yr代码中使用ConfigurationManager.OpenExeConfiguration
来获取配置对象:
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var section = (AppSettingsSection)config.GetSection("UK");
var results = section.Settings["UserName"].Value;
Console.WriteLine(results);