How to: Read connection strings from the Web. config file on msdn Article A demo demonstrates how to read 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 " );
}
I have a project projecta under wwwroot. When I use it, I find that I cannot read my own vcconnectionstring at all and debug the rootwebconfig. connectionstrings. connectionstrings. count is 1, while my web. in config, there is only one connection string with name = "vcconnectionstring. I began to wonder if I could not read it. Is it related to localsqlserver? Use rootwebconfig. connectionstrings. connectionstrings [0] to read connstring and find that it is actually connected to aspnetdb. This is confirmed by connstring. Name. I did not specify localsqlserver in Web. config. Check this demo code. openwebconfiguration (null) causes this problem and prompts that if null is used, it is in null, the root web. config File opened. The root here must be wwwroot. Therefore, set null "~ /"The result is correct. You can read two connectionstrings. One is the custom vcconnectionstring and the other is the localsqlserver defined in machine. config.
by default, localsqlserver always takes precedence over custom connectionstring. That is to say, even if you add your own, remove localsqlserver, and then add a new value, then rootwebconfig. connectionstrings. connectionstrings [0] reads the value of localsqlserver
Of course, there are still some simple methods: configurationmanager. connectionstrings ["vcblogconnectionstring"]. connectionstring can complete the task.