欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#读取配置文件的方法汇总

程序员文章站 2023-01-11 08:22:44
配置文件 ...

配置文件

<?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.net>
  <mailsettings>
   <smtp from="liunian@qq.com">
    <network />
   </smtp>
  </mailsettings>
 </system.net>
</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
    {
      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.net/mailsettings/smtp") as smtpsection;
      console.writeline(section.from);

第四种

第五种

 configurationmanager.appsettings

第六种

 configurationmanager.connectionstrings

当然还有很多......

以上所述就是本文的全部内容了,希望大家能够喜欢。