Reputation: 49
I got a code that can return the ConnectionString from the App.Config
in my VB.Net project. My problem is whether I call online1 or offline2 the offline2 value is being called or more likely a default.
I want to get a connection string base on GetConnectionString([ConnectionString Name])
Public Shared Function GetConnectionString(ByVal strConnection As String) As String
'Declare a string to hold the connection string
Dim sReturn As New String(" ")
Dim connections As ConnectionStringSettingsCollection = ConfigurationManager.ConnectionStrings
'Check to see if they provided a connection string name
If Not String.IsNullOrEmpty(strConnection) Then
For Each connection As ConnectionStringSettings In connections
If connection.Name = strConnection Then
'Retrieve the connection string fromt he app.config
sReturn = connection.ConnectionString
Else
'Since they didnt provide the name of the connection string
'just grab the default on from app.config
sReturn = connection.ConnectionString
End If
Next
End If
Return sReturn
End Function
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="online1" connectionString="SERVER=127.0.0.1; DATABASE=lto_db; UID=root; PASSWORD=;" providerName="MySql.Data.MySqlClient" />
<add name="offline2" connectionString="SERVER=localhost; DATABASE=lto_db; UID=root; PASSWORD=;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
Upvotes: 0
Views: 827
Reputation: 4506
Just use:
Public Shared Function GetConnectionString(ByVal name As String) As String
Dim connStrings = System.Configuration.ConfigurationManager.ConnectionStrings
If String.IsNullOrEmpty(name) Then
If connStrings.Count > 0 Then
Return connStrings(0).ConnectionString
Else
Throw New Exception("No default connection string")
End If
Else
Dim conn = connStrings(name)
If conn Is Nothing Then Throw New Exception("No connection string named " & name)
Return conn.ConnectionString
End If
End Function
You'll need a reference to System.Configuration if you don't have one already
The problem with your code is that if the connection name is null or empty you don't even execute the loop and don't return a default (you just return ""). If they do specify a name and it's not the first then you return the default and exit even if there are more connections to check.
Upvotes: 0