I have a connection string stored within a .config file which I don't know how to read from.
I've searched around and most I found is about how to read key/value pairs stored within AppSetting. But this file is organized differently. All I need is to get the value of ConnectionString.
NOTE: I cannot modify .config
file. It is given to me.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="Assessment.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<Assessment.Properties.Settings>
<setting name="ConnectionString" serializeAs="String"> //This value I need
<value>Provider=Microsoft.ACE.OLEDB.12.0;Data Source=[%CURRENT%]\DB.mdb</value>
</setting>
</Assessment.Properties.Settings>
</userSettings>
</configuration>
The easiest way to read/write AppSettings config file there is a special section in reserved which allows you to do exactly that. Simply add an <appsettings> section and add your data as key/value pairs of the form <add key="xxx" value="xxxx" /> . That's all to create a new app. config file with settings in it.
You can mark the settings as public in the C# project ("Access Modifier" in the property pane of settings) and then you can access it from the vb project (don't forget to add the reference).
To access these values, there is one static class named ConfigurationManager, which has one getter property named AppSettings. We can just pass the key inside the AppSettings and get the desired value from AppSettings section, as shown below. When we implement the code given above, we get the output, as shown below.
There will be Settings class in the namespace of your project (Assessment.Properties.Settings)
The class is autogenerated.
To access your connection string simply use
Assessment.Properties.Settings.Default.ConnectionString
Use the ConfigurationManager.ConnectionStrings property to retrieve connection strings from the application configuration file.
You should be storing your connection strings in the connectionStrings section of the configuration file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With