Extracting the database's name or path from the connection string
' Return the Database name if the input connection string points to a SQL
' Server DB, or the DB path if the connection string points to a Jet (Access) DB
'
' Examples:
' Debug.WriteLine(GetDatabaseName("Provider=Microsoft.Jet.OLEDB.4.0;Data
' Source=D:\MyDB.mdb;")) ' => D:\MyDB.mdb;
' Debug.WriteLine(GetDatabaseName("Provider=SQLOLEDB.1;Data Source=.;User
' ID=sa;Password=;Initial Catalog=MyDB")) ' => MyDB
' Debug.WriteLine(GetDatabaseName("server=(local);database=MyDB;uid=sa;pwd=;")
' ) ' => MyDB
Function GetDatabaseName(ByVal connString As String) As String
Dim lcConnString = connString.ToLower()
' if this is a Jet database, find the index of the "data source" setting
Dim startIndex As Integer
If lcConnString.IndexOf("jet.oledb") > -1 Then
startIndex = lcConnString.IndexOf("data source=")
If startIndex > -1 Then startIndex += 12
Else
' if this is a SQL Server database, find the index of the "initial
' catalog" or "database" setting
startIndex = lcConnString.IndexOf("initial catalog=")
If startIndex > -1 Then
startIndex += 16
Else ' if the "Initial Catalog" setting is not found,
' try with "Database"
startIndex = lcConnString.IndexOf("database=")
If startIndex > -1 Then startIndex += 9
End If
End If
' if the "database", "data source" or "initial catalog" values are not
' found, return an empty string
If startIndex = -1 Then Return ""
' find where the database name/path ends
Dim endIndex As Integer = lcConnString.IndexOf(";", startIndex)
If endIndex = -1 Then endIndex = lcConnString.Length
' return the substring with the database name/path
Return connString.Substring(startIndex, endIndex - startIndex)
End Function