如何从app.config文件中在VS2012 WPF应用程序中获取连接字符串?

10

我正在使用VS2012。我必须将连接字符串保留在app.config中,并从我的cs文件访问它。但是我无法在VS2012中实现这一点。以下是我从网络上找到的,但我认为它仅适用于早期版本的VS,而非VS2012。

app.config文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
   <connectionStrings>
      <add name="DataFormConnection"
            connectionString="Data Source=abcdd;database=xyz;uid=4566;pwd=987"
            providerName="System.Data.SqlClient" />
   </connectionStrings>
</configuration>

我是如何访问它的:

connectionString = ConfigurationManager.ConnectionStrings["DataFormConnection"].ConnectionString;

出现错误:System.Configuration.ConfiguarationSettings 中不存在该类型或名称


为什么这被标记为“ASP.Net”?它是WPF还是ASP.Net?2层还是3层?app.config还是web.config? - ken2k
你的错误信息显示 System.Configuration.ConfigurationSettings,但是你的代码使用的是 ConfigurationManager - 你能否澄清一下你没有在某个地方使用 ConfigurationSettings(我认为这个类是 .NET 1/1.1 版本的)? - Charleh
2个回答

20

前往“引用”并添加一个对System.Configuration的引用。


6

前往References,并添加对System.Configuration的引用。

完成上述步骤后,您就可以引用System.Configuration.ConfigurationManager了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接