我正在編寫一個Windows窗體應用程序,VS2010,NET Framework 4.0,在VB中編碼。我在我的應用程序中使用Microsoft Data Connection Configuration對話框來選擇數據源。它似乎工作正常,並正確創建ConnectionString。但是,新的連接字符串未保存到app.config文件。我沒有寫代碼來保存這個文件,而且我在這個區域盲目搖擺。下面是我使用的代碼:從Windows窗體應用程序中保存新的連接字符串?
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
的MSGBOX顯示了config文件預期的文件名和路徑,但該文件是永遠不會更新。我試過這個從VS2010 IDE運行,直接運行由編譯創建的.exe文件,創建一個安裝程序並安裝程序並運行它(程序本身運行良好),並安裝在不同的機器上。始終保持不變 - 沒有錯誤消息,並且.config文件未更新。
程序正在從appname .exe.config文件中讀取連接字符串。如果我手動編輯exe.config文件,我可以使用不同的連接字符串而不會出現問題。
如果有人可以提供任何指導,我會非常感激!提前致謝。
在這裏找到我自己的答案 - [link](http://thecodemonk.com/2008/02/18/tableadapter-connection-strings/) –