Winform的AppConfig支持自己定义节点,然后来维护一些数据。用来做配置文件一般来说基本够用了:
<configuration>
<configSections>
<section name="User" type="System.Configuration.NameValueSectionHandler"/>
</configSections>
<User>
<add key="Ming" value="2"/>
</User>
下面是一个读取AppConfig的一些方法:
public static List<string> GetConfigList(string sectionname)// 把所有的Key作为List<string >返回
{
NameValueCollection Section = LoadConfig.loadConfig(sectionname);
List<string> Items = new List<string>(); ;
if (Section!= null)
{
for (int k = 0; k < Section.Keys.Count; k++)
{
var item = Section.Keys[k];
Items.Add(Section.Keys[k]);
}
}
return Items;
}
public static string GetConfigFirstValue(string sectionname)//读取只有一条的配置
{
NameValueCollection Section = LoadConfig.loadConfig(sectionname);
List<string> Items = new List<string>(); ;
if (Section != null)
{
return Section.Keys[0].ToString();
}
else
{
return null;
}
}
public static DataTable GetConfigDT(string sectionname)//将配置数据返回为一个DataTable
{
NameValueCollection Section = LoadConfig.loadConfig(sectionname);
DataTable Items=new DataTable() ;
if (Section != null)
{
Items.Columns.Add("Key");
Items.Columns.Add("Value");
for (int k = 0; k < Section.Keys.Count; k++)
{
Items.Rows.Add(Section.Keys[k].ToString(),Section.GetValues(k).GetValue(0).ToString());
}
}
return Items;
}
public static string GetValuebyKey(string sectionname,string key)// 根据Key值得到Value值
{
NameValueCollection Section = LoadConfig.loadConfig(sectionname);
if (Section != null)
{
for (int k = 0; k < Section.Keys.Count; k++)
{
if (Section.Keys[k].ToString() == key)
{
return Section.GetValues(k).GetValue(0).ToString();
}
}
}
return null;
}