位置:首页 > 编程专栏 > C#

C# 读取配置文件 app.config web.config

添加配置文件:App.config or Web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <!--connectionStrings-->
  <connectionStrings>
    <add name="DBConnString1" connectionString="Data Source=127.0.0.1;Initial Catalog=test;uid=sa;pwd=123456789"/>
  </connectionStrings>

  <!--appSettings-->
  <appSettings>
    <add key="DBConnString2" value="Data Source=127.0.0.1;Initial Catalog=test;uid=sa;pwd=123456789" />
  </appSettings>
</configuration>


读取

引用:using System.Configuration;

string conn1 = ConfigurationManager.ConnectionStrings["DBConnString1"].ConnectionString;
string conn2 = ConfigurationManager.ConnectionStrings["DBConnString1"].ToString();
string conn3 = ConfigurationManager.AppSettings["DBConnString2"];


C# 社区推荐