MSDN上How to: Read Connection Strings from the Web.config File的這篇文章用一個小demo示範了如何讀ConnectionString。
Demo Code: System.Configuration.Configuration rootWebConfig =System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
System.Configuration.ConnectionStringSettings connString;
if (0 < rootWebConfig.ConnectionStrings.ConnectionStrings.Count)
{
connString =rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
if (null != connString)
Console.WriteLine("Northwind connection string = \"{0}\"",connString.ConnectionString);
else
Console.WriteLine("No Northwind connection string");
}
我在wwwroot下有一個工程ProjectA,當去用的時候發現根本不能讀出自己的vcConnectionString,調試讀出的rootWebConfig.ConnectionStrings.ConnectionStrings.Count為1,而我的web.config中的確是只有一個name="vcConnectionString"的連接字串。開始懷疑如果讀不出我的來,那麼是不是與LocalSqlServer有關係了呢?使用rootWebConfig.ConnectionStrings.ConnectionStrings[0]讀出connString來發現果然是串連到aspnetdb的,connString.Name更是證實了這點。而我在web.config中根本沒有指定LocalSqlServer。檢查這段demo code,OpenWebConfiguration(null)導致了這個問題出現,提示了說如果使用null的話是In null, the root web.config file opened,這裡的root一定是wwwroot了。於是把null該為"~/"結果就正確了。可以讀出兩條ConnectionString了,一條是我定義的vcConnectionString,一條是machine.config裡定義的LocalSqlServer。
另外,預設情況下LocalSqlServer總是比自訂的connectionString優先。也就是說即使你先add了自己的,然後remove了LocalSqlServer後再add新的值,那麼rootWebConfig.ConnectionStrings.ConnectionStrings[0]讀出的還是LocalSqlServer的值
當然,簡單的方法還是有的:ConfigurationManager.ConnectionStrings["vcBlogConnectionString"].ConnectionString就可以完成任務了.