C#读取配置⽂件的⽅法汇总
配置⽂件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="SQLConfiguration" type="ConfigurationDemo.SQLConfiguration,ConfigurationDemo"/>
<section name="AccountConfiguration" type="ConfigurationDemo.AccountConfiguration,ConfigurationDemo"/>
</configSections>
<SQLConfiguration type="MSSQL" connectionString="server=.;integrated security=sspi;database=Northwind"></SQLConfiguration> <AccountConfiguration>
<users username="liunian" password="123456"></users>
</AccountConfiguration>
<system>
<mailSettings>
<smtp from="liunian@qq">
<network />
</smtp>
</mailSettings>
</system>
</configuration>
第⼀种
关联词语的用法
class SQLConfiguration : ConfigurationSection
{
[ConfigurationProperty("type", IsRequired = true)]
public string Type
{
get { return this["type"].ToString(); }
set { this["type"] = value; }
}
[ConfigurationProperty("connectionString", IsRequired = true)]
读取配置文件失败public string ConnectionString
{
刘若英 陈升
get { return this["connectionString"].ToString(); }
set { this["connectionString"] = value; }
}
}
SQLConfiguration sqlConfig = (SQLConfiguration)ConfigurationManager.GetSection("SQLConfiguration");
章子怡被多少人睡过Console.WriteLine(sqlConfig.Type);
Console.WriteLine(sqlConfig.ConnectionString);
第⼆种
public class AccountConfiguration : ConfigurationSection
{
[ConfigurationProperty("users", IsRequired = true)]
public AccountSectionElement Users
qq不能登陆{
get { return (AccountSectionElement)this["users"]; }
}
}
public class AccountSectionElement : ConfigurationElement
{
[ConfigurationProperty("username", IsRequired = true)]
public string UserName
{
get { return this["username"].ToString(); }
set { this["username"] = value; }
}
[ConfigurationProperty("password", IsRequired = true)]
public string Password
{
get { return this["password"].ToString(); }
set { this["password"] = value; }
}
}
AccountConfiguration accountConfig = (AccountConfiguration)ConfigurationManager.GetSection("AccountConfiguration"); Console.WriteLine(accountConfig.Users.UserName);
Console.WriteLine(accountConfig.Users.Password);白百何资料
第三种
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
SmtpSection section = config.GetSection("system/mailSettings/smtp") as SmtpSection;
Console.WriteLine(section.From);
第四种
第五种
ConfigurationManager.AppSettings
第六种
ConfigurationManager.ConnectionStrings
当然还有很多......
以上所述就是本⽂的全部内容了,希望⼤家能够喜欢。
发布评论