我在wpf项目中有一个配置文件来存储连接字符串。但是,当我尝试获取AppSettings和ConnectionStrings时,将得到null。
WEB.config文件是这样的:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="Trackboard" connectionString="Data Source=(localdb)\v11.0;Initial Catalog=Trackboard;Integrated Security=True;AttachDbFileName=E:\Users\Sean\Workspace\DATABASE\Trackboard.mdf"/> </connectionStrings> <appSettings> <add key="Trackboard" value="Data Source=(localdb)\v11.0;Initial Catalog=Trackboard;Integrated Security=True;AttachDbFileName=E:\Users\Sean\Workspace\DATABASE\Trackboard.mdf"/> </appSettings> </configuration>
我尝试了几种方法:
W1: ConnStr = ConfigurationManager.ConnectionStrings["Trackboard"].ConnectionString; W2: ConnStr = ConfigurationManager.ConnectionStrings[0].ConnectionString; W3: ConnStr = ConfigurationManager.AppSettings["Trackboard"]; W4: ConnStr = ConfigurationManager.AppSettings[0];
他们都没有工作。
但是,这一工作:
ConnStr = @"Data Source=(localdb)\v11.0;Initial Catalog=Trackboard;Integrated Security=True;AttachDbFileName=E:\Users\Sean\Workspace\DATABASE\Trackboard.mdf";
(这意味着我不能使用配置文件,这违反了我的意愿)我需要帮助。
我知道了!我不应该创建一个新的配置文件。项目中有一个默认的app.config文件。现在一切都很好。
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> </configSections> <connectionStrings> <add name="Trackboard.Properties.Settings.TrackboardConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\DATABASE\Trackboard.mdf;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration> private static string ConnStr = ConfigurationManager.ConnectionStrings["Trackboard.Properties.Settings.TrackboardConnectionString"].ConnectionString;