c#

位置:IT落伍者 >> c# >> 浏览文章

在C#中如何读取配置文件[2]


发布日期:2023年09月16日
 
在C#中如何读取配置文件[2]

不同的type不但设置配置节的方式不一样最后访问配置文件的操作上也有差异下面我们就举一个配置文件的例子让它包含这三个不同的type

<?xml version= encoding=utf ?>

<configuration>

<configSections>

<section name=Test type=SystemConfigurationSingleTagSectionHandler/>

<section name=Test type=SystemConfigurationDictionarySectionHandler/>

<section name=Test type=SystemConfigurationNameValueSectionHandler />

</configSections>

<Test setting=Hello setting=World/>

<Test>

<add key=Hello value=World />

</Test>

<Test>

<add key=Hello value=World />

</Test>

</configuration>

我们对上面的自定义配置节进行说明在声明部分使用<section name=Test type=SystemConfigurationSingleTagSectionHandler/>声明了一个配置节它的名字叫 Test类型为SingleTagSectionHandler在设置配置节部分使用 <Test setting=Hello setting=World/>设置了一个配置节它的第一个设置的值是Hello第二个值是World当然还可以有更多其它的两个配 置节和这个类似

下面我们看在程序中如何访问这些自定义的配置节我们用过ConfigurationSettings类的静态方法GetConfig来获取自定义配置节的信息

public static object GetConfig(string sectionName);

下面是访问这三个配置节的代码

//访问配置节Test

IDictionary IDTest = (IDictionary)ConfigurationSettingsGetConfig(Test);

string str = (string)IDTest[setting] + +(string)IDTest[setting];

MessageBoxShow(str); //输出Hello World

//访问配置节Test的方法

string[] values=new string[IDTestCount];

IDTestValuesCopyTo(values);

MessageBoxShow(values[]+ +values[]); //输出Hello World

//访问配置节Test

IDictionary IDTest = (IDictionary)ConfigurationSettingsGetConfig(Test);

string[] keys=new string[IDTestKeysCount];

string[] values=new string[IDTestKeysCount];

IDTestKeysCopyTo(keys);

IDTestValuesCopyTo(values);

MessageBoxShow(keys[]+ +values[]);

//访问配置节Test

NameValueCollection nc=(NameValueCollection)ConfigurationSettingsGetConfig(Test);

MessageBoxShow(ncAllKeys[]ToString()+ +nc[Hello]); //输出Hello World

[] [] []

               

上一篇:Visual C#中轻松浏览数据库记录

下一篇:在C#中如何读取配置文件[1]