获取Web.config的内容

时间:2022-03-31 07:12:33

<web.config>

web.config文件是一个XML文件,它的根结点是<configuration>,在<configuration>节点下的常见子节点有:

<configSections>、<appSettings>、<connectionStrings>和<system.web>。

其中<appSettings>节点主要用于配置一些网站的应用配置信息,而<connectionStrings>节点主要用于配置网站的数据库连接字符串信息。

<appSettings>节点

获取Web.config的内容

后台:

//获取ip
string ip = System.Configuration.ConfigurationManager.AppSettings["server"];

<connectionStrings>节点

<!--连接字符串设置-->
<connectionStrings>
<add name="ConnString" connectionString="Data Source=GAO;Initial Catalog=HBWXDate;User ID=sa;password=sa"></add>
<add name="MysqlConnString" connectionString="server=ip地址;user id=账户;pwd=密码;database=数据库名称"></add>
</connectionStrings>

后台:

//获取连接字符串
string MysqlConnString = ConfigurationManager.ConnectionStrings["MysqlConnString"].ConnectionString;
//根据字符串连接数据库
using (MySql.Data.MySqlClient.MySqlConnection con = new MySql.Data.MySqlClient.MySqlConnection(MysqlConnString))
{
try
{
con.Open();
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.CommandText = sql;
cmd.Connection = con; MySql.Data.MySqlClient.MySqlDataAdapter sqldap = new MySql.Data.MySqlClient.MySqlDataAdapter();
sqldap.SelectCommand = cmd;
System.Data.DataTable dt = new System.Data.DataTable();
sqldap.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
}