'Read ConnectionString from Application Settings in Web.config
I'm working on a .NET Framework 4.5.2 legacy application.
I need the plain ConnectionString of my application, but I don't know how to read it.
Unfortunately the Web.config file of the app, does not have a section "connectionStrings".
Instead, in the Web.config file, there is a section "applicationSettings" which contains the necessary parameters:
<applicationSettings>
<MyApp.Properties.Settings xdt:Transform="Replace">
<setting name="Url" serializeAs="String">
<value>myapp.com</value>
</setting>
<setting name="User" serializeAs="String">
<value>admin</value>
</setting>
<setting name="PW" serializeAs="String">
<value>Password1</value>
</setting>
<setting name="Domain" serializeAs="String">
<value>Fruits</value>
</setting>
<setting name="Port" serializeAs="String">
<value>123</value>
</setting>
<setting name="UseSSL" serializeAs="String">
<value>True</value>
</setting>
</MyApp.Properties.Settings>
</applicationSettings>
I need the plain connection string as a text in notepad - because I need to store the connectionstring in my Azure DevOps environment.
Do you know how to retrieve the connectionString?
By any chance, do you know how to solve this issue?
Solution 1:[1]
I'm not sure if I understood correctly your problem, but I think you should be able to use the ConfigurationManager.AppSettings property to read the values from the Web.config file.
But instead I would add the connection string inside the Configuration section (in the Web.config), like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
..
<connectionStrings>
<add name="MyConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True;Pooling=False" />
</connectionStrings>
<appSettings>
..
</appSettings>
Then is just a matter to get the connection from the ConnectionStrings property: ConfigurationManager.ConnectionString["MyConnection"], and that's it.
If you need further information can see the following links:
Solution 2:[2]
To retrieve the connectionString you can use the following code
string cn=ConfigurationManager.ConnectionStrings[yourConnectionStringName].ConnectionString;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dredg87 |
| Solution 2 | M Rizwan |
