Skip to main content
 首页 » 编程设计

c#之C#中的ConfigurationManager有什么问题吗

2024年02月13日16pander-it

我阅读了许多与配置管理器相关的主题,但无法解决问题。我只想从 Web 应用程序的类库中读取连接字符串和一些应用程序设置键。

我引用了 System.Configuration 类。

这是我的代码:

using System.Configuration; 
 
... 
 
string constr = ConfigurationManager.ConnectionStrings["cbuddydb"].ConnectionString; 
string strUserName = ConfigurationManager.AppSettings["username"]; 
string strPwd = ConfigurationManager.AppSettings["password"]; 

但它似乎是从不同的配置文件中读取的。不是来 self 项目中的 web.config。因为读取的值是错误的。

我的 web.config 如下:

<configuration> 
    <system.web> 
        <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
  <system.data> 
    <connectionStrings> 
      <clear /> 
      <add name="cbuddydb" connectionstring= 
           "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True; 
            User=@username;Password=@password;Option=3" providerName="MySql.Data.MySqlClient" password=""/> 
    </connectionStrings> 
    <appSettings > 
      <clear /> 
      <add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/> 
      <add key="password" value =""/> 
    </appSettings> 
  </system.data> 
</configuration> 

请您参考如下方法:

之所以会这样,是因为配置文件的继承。索引 0 处的连接字符串可能不在您的配置文件中,但它可能已从 machine.config 等继承。查看 ASP.Net 配置文件层次结构和继承:http://msdn.microsoft.com/en-us/library/ms178685.aspx

您可以通过在 web.config 中指定以下内容来清除继承的连接字符串

 <connectionStrings>  
     <clear />   
     <add name=”MyConnString” connectionString=“Whatever“  />  
  </connectionStrings>  

编辑:在您的配置中,将您的 connectionStrings 和 appSettings 标记直接放在配置元素下方。它们不应该在 system.data 元素中。它们是配置元素的直接子元素。并删除 providerName 之后的额外密码属性。我无法验证您的连接字符串,因为我不知道您是如何使用它的。

<configuration> 
  <connectionStrings> 
    <clear /> 
    <add name="cbuddydb"  connectionString= 
       "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True; 
        User=@username;Password=@password;Option=3" providerName="MySql.Data.MySqlClient"/> 
  </connectionStrings> 
 
  <appSettings >         
    <add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/> 
    <add key="password" value =""/> 
  </appSettings> 
 
  <system.data> 
.... 

您应该考虑加密配置文件中的敏感信息,例如密码。