[英]Trying to get String from App.config File
I'm desperately trying to make a working app.config
file in which I want to save the connection strings for my database connections. 我拼命试图制作一个有效的
app.config
文件,在其中我要保存数据库连接的连接字符串。
This is my app.config
file: 这是我的
app.config
文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Con" value="User Id = *******;password=**;data source= (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = ******)(PORT = 1525))(CONNECT_DATA =(SERVER = DEDICATED)(SID = emtst)))"/>
</appSettings>
</configuration>
And when I try to read it here: 当我尝试在这里阅读时:
string connStr = ConfigurationManager.AppSettings["Con"];
this.odacManager = new ODACManager(connStr);
I just get an empty string. 我只是得到一个空字符串。 I'm using
System.Configuration
. 我正在使用
System.Configuration
。
I've also tried to use 我也尝试过使用
ConfigurationManager.Connectionstring["Con"].ConnectionString
but that also didn't work. 但这也不起作用。
You should be using the <connectionStrings>
element in your config file: 您应该在配置文件中使用
<connectionStrings>
元素:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Con"
connectionString="User Id=*******;password=**;data source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = ******)(PORT = 1525))(CONNECT_DATA =(SERVER = DEDICATED)(SID = emtst)))"/>
</connectionStrings>
</configuration>
and then read it out as: 然后将其读出为:
string connStr = ConfigurationManager.ConnectionStrings["Con"].ConnectionString;
Update: 更新:
In .NET, class library projects cannot have their own config files - they won't be used and won't be evaluated at runtime. 在.NET中,类库项目不能拥有自己的配置文件-它们将不会被使用,并且不会在运行时进行评估。
If your class library needs any configuration, you need to put that configuration into the host application's app.config
(or web.config
) so that the class library can find it there (and use it). 如果您的类库需要任何配置,则需要将该配置放入主机应用程序的
app.config
(或web.config
)中,以便类库可以在其中找到(并使用它)。
尝试
System.Configuration.ConfigurationSettings.AppSettings["Con"].ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.