Save a new connection string from within a windows forms app?
开发者_JAVA百科I'm writing a Windows Forms app, VS2010, NET Framework 4.0, coding in VB. I'm using the Microsoft Data Connection Configuration dialog in my app to choose a data source. It seems to work fine and creates the ConnectionString correctly. However, the new connection string is not being saved to the app.config file. I did not write the code to save the file and I'm staggering around blindly in this area. Here's the code I'm using:
Public Sub SaveConnectionString(ByVal strConnectionName As String, strConnectionString As String)
Dim Config As Configuration
Dim Section As ConnectionStringsSection
Dim Setting As ConnectionStringSettings
Dim ConnectionFullName As String
'There is no inbuilt way to change application
'setting values in the config file.
'So that needs to be done manually by calling config section object.
Try
'Concatenate the full settings name
'This differs from Jakob Lithner. Runtime Connection Wizard
'The ConnectionFullName needs to
'refer to the Assembly calling this DLL
ConnectionFullName = String.Format("{0}.MySettings.{1}", _
System.Reflection.Assembly.GetCallingAssembly.EntryPoint.DeclaringType.Namespace, strConnectionName)
'Point out the objects to manipulate
Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Section = CType(Config.GetSection("connectionStrings"), _
ConnectionStringsSection)
Setting = Section.ConnectionStrings(ConnectionFullName)
MsgBox("To File: " & Config.FilePath.ToString & vbCrLf &
"Conn. String: " & strConnectionString & vbCrLf &
"Conn. Name: " & strConnectionName,
MsgBoxStyle.Information, "Saving Connection String...")
'Ensure connection setting is defined
'(Note: A default value must be set to save the connection setting!)
If IsNothing(Setting) Then Throw New Exception("There is no connection with this name defined in the config file.")
'Set value and save it to the config file
'This differs from Jakob Lithner. Runtime Connection Wizard
'We only want to save the modified portion of the config file
Setting.ConnectionString = strConnectionString
Config.Save(ConfigurationSaveMode.Full, True)
Catch ex As Exception
End Try
End Sub
The MsgBox shows the expected file name and path for the .config file but the file is never updated. I've tried this running from the VS2010 IDE, directly running the .exe file created by the compile, creating a Setup and installing the program and running that (program itself runs fine), and installing on a different machine. Always the same - no error messages and the .config file is not updated.
The program is reading the connection string from the appname.exe.config file. If I edit the exe.config file manually I can use different connection strings without problems.
If anyone can offer any guidance, I'll be VERY appreciative! Thanks in advance.
A fair number of page views to my question, but no answers ventured. Fortunately I found my own answer. Thanks to http://www.thecodemonk.com/2008/02/18/tableadapter-connection-strings for this simple solution.
Don't even try to save to the application setting "AppNameConnectionString". Instead, just save the desired connection string as a user setting, i.e. "ActiveConnectionString" of type string. I replaced the whole block of code I quoted in my original question with this
My.Settings.ActiveConnectionString = strConn ' previously built conn string
My.Settings.Save()
What allows this user setting to become the active connection string are the events associated with .Net managing the settings. On the Project settings there is a button "view code" to access the event handlers of the settings. In the SettingsLoaded event, just set the app connection string setting to your user connection string setting:
Private Sub MySettings_SettingsLoaded(sender As Object, e As System.Configuration.SettingsLoadedEventArgs) Handles Me.SettingsLoaded
Me.Item("MyAppNameConnectionString") = Me.Item("ActiveConnectionString")
End Sub
That's all it takes for your user setting to become the working connection string when the app loads.
Add another event handler in the Settings code and when you save a new connection string from within the app it will be instantly activated!
Private Sub MySettings_PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Handles Me.PropertyChanged
If e.PropertyName = "ActiveConnectionString" Then
Me.Item("MyAppNameConnectionString") = Me.Item("ActiveConnectionString")
End If
End Sub
Thanks again to TheCodeMonk for sharing this stunningly simple, but apparently very elusive solution!
精彩评论